sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
streamlit/streamlit:e2e_playwright/st_plotly_chart_dimensions_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import check_top_level_class, get_element_by_key def test_check_top_level_class(app: Page): """Check that the top level class is correctly set.""" check_top_level_class(app, "stPlotlyChart") # Only run on chromium to reduce test time since visual differences between browsers # should be minimal for dimension tests @pytest.mark.only_browser("chromium") def test_plotly_dimensions(app: Page, assert_snapshot: ImageCompareFunction): """Tests that width and height parameters work correctly.""" plotly_elements = app.get_by_test_id("stPlotlyChart") expect(plotly_elements).to_have_count(8) # Width parameter tests assert_snapshot(plotly_elements.nth(0), name="st_plotly_chart-width_content") assert_snapshot(plotly_elements.nth(1), name="st_plotly_chart-width_stretch") assert_snapshot(plotly_elements.nth(2), name="st_plotly_chart-width_400px") assert_snapshot(plotly_elements.nth(3), name="st_plotly_chart-width_1000px_content") # Height parameter tests assert_snapshot(plotly_elements.nth(4), name="st_plotly_chart-height_content") # For height="stretch", snapshot the entire container to verify stretching behavior stretch_container = get_element_by_key(app, "test_height_stretch") assert_snapshot(stretch_container, name="st_plotly_chart-height_stretch") assert_snapshot(plotly_elements.nth(6), name="st_plotly_chart-height_300px") assert_snapshot(plotly_elements.nth(7), name="st_plotly_chart-height_600px_content") def test_plotly_content_width_fullscreen( themed_app: Page, assert_snapshot: ImageCompareFunction ): """Test fullscreen behavior with width='content'.""" index = 0 # First chart with width='content' themed_app.get_by_test_id("stPlotlyChart").nth(index).hover() fullscreen_button = themed_app.locator('[data-title="Fullscreen"]').nth(index) fullscreen_button.hover() fullscreen_button.click() # Wait for fullscreen mode to activate expect(themed_app.get_by_test_id("stFullScreenFrame").nth(index)).to_have_css( "position", "fixed" ) assert_snapshot( themed_app.get_by_test_id("stPlotlyChart").nth(index), name="st_plotly_chart-content_width_fullscreen", ) fullscreen_button = themed_app.locator('[data-title="Close fullscreen"]').nth(0) fullscreen_button.hover() fullscreen_button.click() # Wait for fullscreen mode to deactivate expect(themed_app.get_by_test_id("stFullScreenFrame").nth(index)).not_to_have_css( "position", "fixed" ) assert_snapshot( themed_app.get_by_test_id("stPlotlyChart").nth(index), name="st_plotly_chart-content_width_exited_fullscreen", ) def test_plotly_stretch_width_fullscreen( themed_app: Page, assert_snapshot: ImageCompareFunction ): """Test fullscreen behavior with width='stretch'.""" index = 1 # Second chart with width='stretch' themed_app.get_by_test_id("stPlotlyChart").nth(index).hover() fullscreen_button = themed_app.locator('[data-title="Fullscreen"]').nth(index) fullscreen_button.hover() fullscreen_button.click() # Wait for fullscreen mode to activate expect(themed_app.get_by_test_id("stFullScreenFrame").nth(index)).to_have_css( "position", "fixed" ) assert_snapshot( themed_app.get_by_test_id("stPlotlyChart").nth(index), name="st_plotly_chart-stretch_width_fullscreen", ) fullscreen_button = themed_app.locator('[data-title="Close fullscreen"]').nth(0) fullscreen_button.hover() fullscreen_button.click() # Wait for fullscreen mode to deactivate expect(themed_app.get_by_test_id("stFullScreenFrame").nth(index)).not_to_have_css( "position", "fixed" ) assert_snapshot( themed_app.get_by_test_id("stPlotlyChart").nth(index), name="st_plotly_chart-stretch_width_exited_fullscreen", )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_plotly_chart_dimensions_test.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/appnode_hierarchy.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ An app that exercises AppNode hierarchy changes. - Swap an element with a different element in-place - Insert an element between two others - Simulate a long computation (with elements turning stale) - Use st.empty() placeholder to update content in place The paired Playwright test ensures only expected elements are visible and no stale duplicates remain after updates/reruns. """ from __future__ import annotations import time import streamlit as st mode = st.selectbox( "Choose scenario", [ "none", "swap_element", "insert_between", "long_compute", "placeholder_updates", "simple_transient_spinner", "complex_transient_spinner", "chat_transient_spinner", ], key="scenario_mode", ) def render_swap_element() -> None: # Swap: previously a text becomes a markdown (different element type) element = st.markdown("initial element") element.text("swapped element") def render_insert_between() -> None: # Insert an element in between two others st.markdown("top") element_2 = st.markdown("between") st.markdown("bottom") element_2.markdown("inserted element") def render_long_compute() -> None: st.markdown("top") st.markdown("second") if st.button("run long compute"): time.sleep(5) else: st.markdown("second to last") st.markdown("bottom") def render_placeholder_updates() -> None: st.markdown("placeholder-top") ph = st.empty() st.markdown("placeholder-bottom") if st.button("update placeholder"): ph.markdown("placeholder-filled") def render_simple_transient_spinner() -> None: st.button("Rerun") if "has_ran" not in st.session_state: with st.spinner("Spinner (delta path 0 0)"): time.sleep(5) # Just to make the bug easier to see. st.write("Hello world 1! (delta path 0 1)") st.session_state.has_ran = True else: st.write("Hello world 2! (delta path 0 0)") time.sleep(5) # Just to make the bug easier to see. del st.session_state.has_ran def render_complex_transient_spinner() -> None: if st.button("Rerun with spinners"): st.session_state.has_ran = True if st.button("Rerun without spinners"): st.session_state.has_ran = False if st.session_state.get("has_ran", True): with st.spinner("Loading..."): time.sleep(0.5) for i in range(2): time.sleep(1) st.write(i) "some text" st.button("Rerun 1") with st.spinner("Loading..."): time.sleep(0.5) for i in range(2): time.sleep(0.3) st.write(i) "some text" st.button("Rerun 2") else: for i in range(2): time.sleep(1) st.write(i) "some text" st.button("Rerun 1") for i in range(2): time.sleep(1) st.write(i) "some text" st.button("Rerun 2") def render_chat_transient_spinner() -> None: if "messages" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if prompt := st.chat_input("Say something"): st.session_state.messages.append({"role": "user", "content": prompt}) st.chat_message("user").write(prompt) with st.chat_message("assistant"): with st.spinner("Thinking..."): time.sleep(3) st.session_state.messages.append( {"role": "assistant", "content": f"Echo: {prompt}"} ) st.write(f"Echo: {prompt}") if mode == "swap_element": render_swap_element() elif mode == "insert_between": render_insert_between() elif mode == "long_compute": render_long_compute() elif mode == "placeholder_updates": render_placeholder_updates() elif mode == "simple_transient_spinner": render_simple_transient_spinner() elif mode == "complex_transient_spinner": render_complex_transient_spinner() elif mode == "chat_transient_spinner": render_chat_transient_spinner()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/appnode_hierarchy.py", "license": "Apache License 2.0", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/appnode_hierarchy_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction, wait_for_app_run from e2e_playwright.shared.app_utils import get_button, get_selectbox def _select_mode(app: Page, mode: str) -> None: selectbox = get_selectbox(app, "Choose scenario").locator("input").first selectbox.fill(mode) selectbox.press("Enter") wait_for_app_run(app) def test_swap_element_replaces_in_place_without_stale(app: Page) -> None: _select_mode(app, "swap_element") # Expect initial element to not be visible expect(app.get_by_text("initial element")).not_to_be_visible() expect(app.get_by_text("swapped element")).to_be_visible() def test_insert_between_adds_only_one_element_in_between(app: Page) -> None: _select_mode(app, "insert_between") expect(app.get_by_text("between", exact=True)).not_to_be_visible() texts = [ "top", "inserted element", "bottom", ] for index, text in enumerate(texts): expect(app.get_by_test_id("stMarkdown").nth(index)).to_have_text(text) def test_long_compute_shows_spinner_only_during_run( app: Page, assert_snapshot: ImageCompareFunction ) -> None: _select_mode(app, "long_compute") texts = [ "top", "second", ] disappearing_texts = [ "second to last", ] stale_texts = [ "bottom", ] for index, text in enumerate(texts + disappearing_texts + stale_texts): expect(app.get_by_test_id("stMarkdown").nth(index)).to_have_text(text) get_button(app, "run long compute").click() # we need to wait for the elements to be stale and the animation to complete # Unfortunately, we have to rely on a timeout here. app.wait_for_timeout(1000) # elements are still there for index, text in enumerate(texts + disappearing_texts + stale_texts): expect(app.get_by_test_id("stMarkdown").nth(index)).to_have_text(text) for text in disappearing_texts + stale_texts: expect( app.get_by_test_id("stElementContainer").filter(has_text=text) ).to_have_attribute("data-stale", "true") # snapshot the main container to show the stale elements faded main = app.get_by_test_id("stVerticalBlock") assert_snapshot(main, name="appnode_hierarchy-long_compute") wait_for_app_run(app) # check that the appropriate texts have disappeared expect(app.get_by_text("second to last")).not_to_be_visible() for index, text in enumerate(texts + stale_texts): expect(app.get_by_test_id("stMarkdown").nth(index)).to_have_text(text) def test_placeholder_updates_do_not_leave_stale_elements(app: Page) -> None: _select_mode(app, "placeholder_updates") expect(app.get_by_test_id("stMarkdown").nth(0)).to_have_text("placeholder-top") expect(app.get_by_test_id("stMarkdown").nth(1)).to_have_text("placeholder-bottom") get_button(app, "update placeholder").click() wait_for_app_run(app) expect(app.get_by_test_id("stMarkdown").nth(0)).to_have_text("placeholder-top") expect(app.get_by_test_id("stMarkdown").nth(1)).to_have_text("placeholder-filled") expect(app.get_by_test_id("stMarkdown").nth(2)).to_have_text("placeholder-bottom") def test_simple_transient_spinner_does_not_leave_stale_elements(app: Page) -> None: _select_mode(app, "simple_transient_spinner") # Initial state expect(app.get_by_text("Hello world 1! (delta path 0 1)")).to_be_visible() get_button(app, "Rerun").click() # The app sleeps for 5s in the else block. # We check for stale elements after 0.5s. app.wait_for_timeout(500) expect(app.get_by_text("Hello world 2! (delta path 0 0)")).to_be_visible() # Verify no stale elements. We don't wait because the script run will eventually remove the stale elements. expect(app.locator("[data-stale='true']")).to_have_count(0, timeout=1) expect(app.get_by_text("Hello world 1! (delta path 0 1)")).not_to_be_visible() def test_complex_transient_spinner_interrupted_does_not_leave_stale_elements( app: Page, ) -> None: _select_mode(app, "complex_transient_spinner") # Run without spinners first get_button(app, "Rerun without spinners").click() wait_for_app_run(app) # Run with spinners get_button(app, "Rerun with spinners").click() # Interrupt it (run without spinners) # This button might be disabled if we don't act fast or if the app blocks. # Assuming standard behavior where we can interrupt. get_button(app, "Rerun without spinners").click() wait_for_app_run(app) # Verify no unexpected stale element out of order. # Verify no stale elements. We don't wait because the script run will eventually remove the stale elements. expect(app.locator("[data-stale='true']")).to_have_count(0, timeout=1) expect(app.get_by_text("some text")).to_have_count(2) def test_chat_transient_spinner_does_not_leave_stale_elements(app: Page) -> None: _select_mode(app, "chat_transient_spinner") chat_input = app.get_by_test_id("stChatInput").locator("textarea") # Type content and enter chat_input.fill("Message 1") chat_input.press("Enter") wait_for_app_run(app) expect(app.get_by_text("Echo: Message 1")).to_be_visible() # Type more content and enter chat_input.fill("Message 2") chat_input.press("Enter") # Wait 0.5s and verify no stale elements app.wait_for_timeout(500) # Verify no stale elements. We don't wait because the script run will eventually remove the stale elements. expect(app.locator("[data-stale='true']")).to_have_count(0, timeout=1) wait_for_app_run(app) expect(app.get_by_text("Echo: Message 2")).to_be_visible()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/appnode_hierarchy_test.py", "license": "Apache License 2.0", "lines": 128, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/bidi_components/basics.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import time from typing import TYPE_CHECKING, Any import pandas as pd import streamlit as st if TYPE_CHECKING: from streamlit.components.v2.bidi_component import BidiComponentResult from streamlit.elements.lib.layout_utils import Height, Width from streamlit.runtime.state.common import WidgetCallback st.header("Custom Components v2 - Basics") # --------------------------------------------------------------------------- # Empty content: component with no HTML/CSS/JS should not error # --------------------------------------------------------------------------- _EMPTY_CMP = st.components.v2.component("bidi_empty_content", isolate_styles=False) with st.container(key="empty_component_container"): st.subheader("Empty content") _EMPTY_CMP(key="empty_component") st.write("After empty component") # --------------------------------------------------------------------------- # Shared: simple stateful component (range + text) used in multiple sections # --------------------------------------------------------------------------- _STATEFUL_JS = """ let hasMounted = {} export default function(component) { const { parentElement, setStateValue, data, key } = component const rangeInput = parentElement.querySelector('#range') const textInput = parentElement.querySelector('#text') const hasMountedForKey = hasMounted[key] if (typeof data?.initialRange !== 'undefined' && !hasMountedForKey) { rangeInput.value = String(data.initialRange) } if (typeof data?.initialText !== 'undefined' && !hasMountedForKey) { textInput.value = String(data.initialText) } const handleRangeChange = (event) => { setStateValue('range', event.target.value) } const handleTextChange = (event) => { setStateValue('text', event.target.value) } rangeInput.addEventListener('change', handleRangeChange) textInput.addEventListener('input', handleTextChange) hasMounted[key] = true return () => { rangeInput.removeEventListener('change', handleRangeChange) textInput.removeEventListener('input', handleTextChange) } } """ _STATEFUL_HTML = """ <div> <label for="range">Range</label> <input type="range" id="range" min="0" max="100" value="50" /> <label for="text">Text</label> <input type="text" id="text" value="Text input" /> <!-- Accessible labels used for selection in tests (no data-testids) --> </div> """ _STATEFUL_CMP = st.components.v2.component( "bidi_stateful", js=_STATEFUL_JS, html=_STATEFUL_HTML, ) def stateful_component( *, key: str | None = None, data: Any | None = None, on_range_change: WidgetCallback | None = None, on_text_change: WidgetCallback | None = None, width: Width = "stretch", height: Height = "content", default: dict[str, Any] | None = None, ) -> BidiComponentResult: return _STATEFUL_CMP( key=key, data=data, on_range_change=on_range_change, on_text_change=on_text_change, width=width, height=height, default=default, ) # --------------------------------------------------------------------------- # Shared: trigger component (foo/bar/both) # --------------------------------------------------------------------------- _TRIGGER_JS = """ export default function(component) { const { parentElement, setTriggerValue } = component const handleClickFoo = () => { setTriggerValue('foo', true) } const handleClickBar = () => { setTriggerValue('bar', true) } const handleClickBoth = () => { setTriggerValue('foo', true); setTriggerValue('bar', true) } const fooButton = parentElement.querySelector('#foo-button') const barButton = parentElement.querySelector('#bar-button') const bothButton = parentElement.querySelector('#both-button') fooButton.addEventListener('click', handleClickFoo) barButton.addEventListener('click', handleClickBar) bothButton.addEventListener('click', handleClickBoth) return () => { fooButton.removeEventListener('click', handleClickFoo) barButton.removeEventListener('click', handleClickBar) bothButton.removeEventListener('click', handleClickBoth) } } """ _TRIGGER_HTML = """ <div> <button id="foo-button">Trigger foo</button> <button id="bar-button">Trigger bar</button> <button id="both-button">Trigger both</button> </div> """ _TRIGGER_CMP = st.components.v2.component( "bidi_trigger", js=_TRIGGER_JS, html=_TRIGGER_HTML ) def trigger_component( *, key: str | None = None, data: Any | None = None, on_foo_change: WidgetCallback | None = None, on_bar_change: WidgetCallback | None = None, ) -> BidiComponentResult: return _TRIGGER_CMP( key=key, data=data, on_foo_change=on_foo_change, on_bar_change=on_bar_change, ) # --------------------------------------------------------------------------- # Shared: form/fragment component used inside contexts # --------------------------------------------------------------------------- _CTX_JS = """ export default function(component) { const { parentElement, setStateValue, setTriggerValue, data } = component const contextName = data?.contextName ? String(data.contextName) : '' const textInput = parentElement.querySelector('#text-input') const setTextBtn = parentElement.querySelector('#set-text-btn') const triggerBtn = parentElement.querySelector('#trigger-btn') if (setTextBtn) setTextBtn.textContent = `Set text${contextName ? ` (${contextName})` : ''}` if (triggerBtn) triggerBtn.textContent = `Trigger click${contextName ? ` (${contextName})` : ''}` const onSetText = () => { const value = (textInput && 'value' in textInput) ? textInput.value : '' setStateValue('text', value) } const onTrigger = () => { setTriggerValue('clicked', true) } setTextBtn?.addEventListener('click', onSetText) triggerBtn?.addEventListener('click', onTrigger) return () => { setTextBtn?.removeEventListener('click', onSetText) triggerBtn?.removeEventListener('click', onTrigger) } } """ _CTX_HTML = """ <label for="text-input">Inner Text</label> <input id="text-input" type="text" value="hello" /> <div style="margin-top: 0.5rem; display: flex; gap: 0.5rem;"> <button id="set-text-btn">Set text</button> <button id="trigger-btn">Trigger click</button> </div> """ _CTX_CMP = st.components.v2.component( name="bidi_ctx", js=_CTX_JS, html=_CTX_HTML, ) def ctx_component( *, key: str | None = None, data: Any | None = None, on_text_change: WidgetCallback | None = None, on_clicked_change: WidgetCallback | None = None, ) -> BidiComponentResult: return _CTX_CMP( key=key, data=data, on_text_change=on_text_change, on_clicked_change=on_clicked_change, ) with st.container(): st.subheader("Stateful") if "stateful_range_change_count" not in st.session_state: st.session_state.stateful_range_change_count = 0 if "stateful_text_change_count" not in st.session_state: st.session_state.stateful_text_change_count = 0 def _stateful_handle_range_change() -> None: st.session_state.stateful_range_change_count += 1 def _stateful_handle_text_change() -> None: st.session_state.stateful_text_change_count += 1 stateful_result = stateful_component( key="stateful_component_1", on_range_change=_stateful_handle_range_change, on_text_change=_stateful_handle_text_change, ) st.write(f"Result: {stateful_result}") st.text(f"session_state: {st.session_state.get('stateful_component_1')}") st.write(f"Range change count: {st.session_state.stateful_range_change_count}") st.write(f"Text change count: {st.session_state.stateful_text_change_count}") st.divider() with st.container(): st.subheader("Trigger") if "trigger_foo_count" not in st.session_state: st.session_state.trigger_foo_count = 0 if "trigger_bar_count" not in st.session_state: st.session_state.trigger_bar_count = 0 if "trigger_last_on_foo_change_processed" not in st.session_state: st.session_state.trigger_last_on_foo_change_processed = None if "trigger_last_on_bar_change_processed" not in st.session_state: st.session_state.trigger_last_on_bar_change_processed = None def _handle_foo_change() -> None: st.session_state.trigger_foo_count += 1 st.session_state.trigger_last_on_foo_change_processed = time.strftime( "%H:%M:%S" ) def _handle_bar_change() -> None: st.session_state.trigger_bar_count += 1 st.session_state.trigger_last_on_bar_change_processed = time.strftime( "%H:%M:%S" ) trigger_result = trigger_component( key="trigger_component_1", on_foo_change=_handle_foo_change, on_bar_change=_handle_bar_change, ) st.write(f"Result: {trigger_result}") st.write(f"Foo count: {st.session_state.trigger_foo_count}") st.write( f"Last on_foo_change callback processed at: {st.session_state.trigger_last_on_foo_change_processed}" ) st.write(f"Bar count: {st.session_state.trigger_bar_count}") st.write( f"Last on_bar_change callback processed at: {st.session_state.trigger_last_on_bar_change_processed}" ) st.text(f"Session state: {st.session_state.get('trigger_component_1')}") st.button("st.button trigger") st.divider() with st.container(): st.subheader("Form context (defer state; triggers ignored by CCv2 semantics)") if "form_text_changes" not in st.session_state: st.session_state.form_text_changes = 0 if "form_clicked_changes" not in st.session_state: st.session_state.form_clicked_changes = 0 def _handle_form_text_change() -> None: st.session_state.form_text_changes += 1 def _handle_form_clicked_change() -> None: # This should not be invoked for CCv2 triggers inside forms. st.session_state.form_clicked_changes += 1 with st.form(key="bidi_form", clear_on_submit=False): form_result = ctx_component( key="in_form", data={"contextName": "Form"}, on_text_change=_handle_form_text_change, on_clicked_change=_handle_form_clicked_change, ) st.form_submit_button("Submit Form") st.write(f"Form Result: {form_result}") st.text(f"Form session state: {st.session_state.get('in_form')}") st.write(f"Form Text changes: {st.session_state.form_text_changes}") st.write(f"Form Clicked count: {st.session_state.form_clicked_changes}") st.divider() with st.container(): st.subheader("Fragment context (partial reruns and local counters)") if "frag_text_changes" not in st.session_state: st.session_state.frag_text_changes = 0 if "frag_clicked_changes" not in st.session_state: st.session_state.frag_clicked_changes = 0 if "runs" not in st.session_state: st.session_state.runs = 0 st.session_state.runs += 1 @st.fragment() def render_fragment() -> None: frag_result = ctx_component( key="in_fragment", data={"contextName": "Fragment"}, on_text_change=lambda: _inc("frag_text_changes"), on_clicked_change=lambda: _inc("frag_clicked_changes"), ) st.write(f"Fragment Result: {frag_result}") st.text(f"Fragment session state: {st.session_state.get('in_fragment')}") st.write(f"Fragment Text changes: {st.session_state.frag_text_changes}") st.write(f"Fragment Clicked count: {st.session_state.frag_clicked_changes}") def _inc(name: str) -> None: st.session_state[name] = int(st.session_state.get(name, 0)) + 1 render_fragment() st.write(f"Runs: {st.session_state.runs}") st.divider() with st.container(): st.subheader("Remount behavior (unmount/remount sequence with persistent state)") def _remount_stateful_component( *, key: str, ) -> BidiComponentResult: # Resolve initial values: prefer session_state if available, else fall back to default values state_value = st.session_state.get(key) initial_defaults: dict[str, Any] = {"range": 10, "text": "hello"} if isinstance(state_value, dict): initial_defaults.update(state_value) return stateful_component( key=key, on_range_change=lambda: _inc("remount_range_change_count"), on_text_change=lambda: _inc("remount_text_change_count"), default={"range": 10, "text": "hello"}, data={ "initialRange": initial_defaults.get("range", 10), "initialText": initial_defaults.get("text", "hello"), }, ) if "remount_range_change_count" not in st.session_state: st.session_state.remount_range_change_count = 0 if "remount_text_change_count" not in st.session_state: st.session_state.remount_text_change_count = 0 # Standard unmount/remount pattern if st.button("Create some elements to unmount component"): for _ in range(3): time.sleep(1) st.write("Another element") remount_key = "remount_component_1" st.write("Above the component") remount_result = _remount_stateful_component(key=remount_key) st.write(f"Result: {remount_result}") st.text(f"session_state: {st.session_state.get(remount_key)}") st.write(f"Range change count: {st.session_state.remount_range_change_count}") st.write(f"Text change count: {st.session_state.remount_text_change_count}") st.divider() with st.container(): st.subheader("Basic (broad CSS + mixed state/trigger)") # Default values mirror the original default app _BASIC_DEFAULT = { "formValues": { "range": 20, "text": "Text input", }, } _BASIC_JS = """ export default function(component) { const { data, parentElement, setStateValue, setTriggerValue } = component const form = parentElement.querySelector("form") const handleSubmit = (event) => { event.preventDefault() const formValues = { range: event.target.range.value, text: event.target.text.value, } setStateValue("formValues", formValues) } form.addEventListener("submit", handleSubmit) const handleClick = () => { setTriggerValue("clicked", true) } parentElement.addEventListener("click", handleClick) return () => { form.removeEventListener("submit", handleSubmit) parentElement.removeEventListener("click", handleClick) } } """ _BASIC_HTML = f""" <h1>Hello World</h1> <form> <label for="range">Range</label> <input type="range" id="range" name="range" min="0" max="100" value="{_BASIC_DEFAULT["formValues"]["range"]}" /> <label for="text">Text</label> <input type="text" id="text" name="text" value="{_BASIC_DEFAULT["formValues"]["text"]}" /> <button type="submit">Submit form</button> <!-- Accessible labels used for selection in tests (no data-testids) --> </form> """ # Intentionally broad CSS rules to verify style isolation _BASIC_CSS = """ div { color: var(--st-primary-color); background-color: var(--st-background-color); } """ _BASIC_CMP = st.components.v2.component( name="bidi_basic", js=_BASIC_JS, html=_BASIC_HTML, css=_BASIC_CSS, ) def basic_component( *, key: str | None = None, data: Any | None = None, on_formValues_change: WidgetCallback | None = None, # noqa: N803 on_clicked_change: WidgetCallback | None = None, default: dict[str, Any] | None = None, ) -> BidiComponentResult: return _BASIC_CMP( key=key, data=data, on_formValues_change=on_formValues_change, on_clicked_change=on_clicked_change, default=default, ) if "basic_click_count" not in st.session_state: st.session_state.basic_click_count = 0 def _handle_basic_click() -> None: st.session_state.basic_click_count += 1 # Changes of formValues are captured but do not update an extra counter def _handle_basic_change() -> None: pass basic_result = basic_component( key="basic_component_1", data={"label": "Some data from python"}, on_formValues_change=_handle_basic_change, on_clicked_change=_handle_basic_click, default=_BASIC_DEFAULT, ) st.write(f"Result: {basic_result}") st.text(f"session_state: {st.session_state.get('basic_component_1')}") st.write(f"Click count: {st.session_state.basic_click_count}") st.divider() with st.container(): st.subheader("Global hotkey interface") if "hotkey_runs" not in st.session_state: st.session_state.hotkey_runs = 0 st.session_state.hotkey_runs += 1 _HOTKEY_JS = """ export default function(component) { const { parentElement, setStateValue } = component const form = parentElement.querySelector("form") const input = parentElement.querySelector("#hotkey-text") const handleSubmit = (event) => { event.preventDefault() setStateValue("text", input?.value ?? "") } form.addEventListener("submit", handleSubmit) return () => { form.removeEventListener("submit", handleSubmit) } } """ _HOTKEY_HTML = """ <form> <label for="hotkey-text">Hotkey Text</label> <input type="text" id="hotkey-text" name="hotkey-text" value="" /> <button type="submit">Submit</button> </form> """ _HOTKEY_CMP = st.components.v2.component( name="bidi_hotkey_regression", js=_HOTKEY_JS, html=_HOTKEY_HTML, ) def hotkey_regression_component(*, key: str) -> BidiComponentResult: return _HOTKEY_CMP(key=key) hotkey_result = hotkey_regression_component(key="hotkey_regression_component") st.write(f"Hotkey runs: {st.session_state.hotkey_runs}") st.write(f"Result: {hotkey_result}") st.divider() with st.container(): st.subheader("Arrow serialization") # Component that receives two DataFrames and a label and renders # their schema and row data, verifying Arrow serialization. _ARROW_JS = """ export default function(component) { const { parentElement, data } = component const root = parentElement.querySelector("#my-arrow-component") const { df, df2, label } = data; const cols = df.schema.fields.map((f) => f.name); const rows = df.toArray(); const cols2 = df2.schema.fields.map((f) => f.name); const rows2 = df2.toArray(); root.innerText = `Label: ${label}\nCols: ${cols}\nRows: ${rows}\nCols2: ${cols2}\nRows2: ${rows2}` } """ _ARROW_HTML = """ <div id="my-arrow-component"></div> """ _ARROW_CMP = st.components.v2.component( name="my_arrow_component", js=_ARROW_JS, html=_ARROW_HTML, ) def arrow_component(*, key: str, data: Any) -> BidiComponentResult: return _ARROW_CMP(key=key, data=data) df = pd.DataFrame({"a": [1, 2, 3]}) df2 = pd.DataFrame({"b": [4, 5, 6]}) arrow_component( key="my_arrow_component", data={ "df": df, "df2": df2, "label": "Hello World", }, )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/bidi_components/basics.py", "license": "Apache License 2.0", "lines": 499, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/bidi_components/basics_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Locator, Page, expect from e2e_playwright.shared.app_utils import ( click_form_button, expect_no_exception, get_element_by_key, ) from e2e_playwright.shared.input_utils import ( expect_global_hotkeys_not_fired, type_common_characters_into_input, ) def section(app: Page, heading_name: str) -> Locator: """Return the stLayoutWrapper that contains the given heading. Uses a containment filter to scope DOM queries to the specific section. """ heading = app.get_by_role("heading", name=heading_name, exact=True) return app.locator("[data-testid='stLayoutWrapper']").filter(has=heading).first def test_empty_content_does_not_crash(app: Page) -> None: """CCv2 should allow empty component definitions (no js/html/css) without errors.""" empty_container = get_element_by_key(app, "empty_component_container") expect(empty_container.get_by_role("heading", name="Empty content")).to_be_visible() expect_no_exception(app) expect(empty_container.get_by_test_id("stBidiComponentRegular")).to_have_count(1) expect(empty_container.get_by_text("After empty component")).to_be_visible() def test_stateful_interactions(app: Page) -> None: # Initial values stateful = section(app, "Stateful") expect(stateful.get_by_label("Range").first).to_have_value("50") expect(stateful.get_by_label("Text").first).to_have_value("Text input") expect( stateful.get_by_text("Result: {'range': None, 'text': None}") ).to_be_visible() expect(stateful.get_by_text("session_state: {}")).to_be_visible() expect(stateful.get_by_text("Range change count: 0")).to_be_visible() expect(stateful.get_by_text("Text change count: 0")).to_be_visible() # Change Range value (only range changes) stateful.get_by_label("Range").first.fill("10") expect(stateful.get_by_label("Range").first).to_have_value("10") expect( stateful.get_by_text("Result: {'range': '10', 'text': None}") ).to_be_visible() expect(stateful.get_by_text("session_state: {'range': '10'}")).to_be_visible() expect(stateful.get_by_text("Range change count: 1")).to_be_visible() expect(stateful.get_by_text("Text change count: 0")).to_be_visible() # Change Text value (only text changes) stateful.get_by_label("Text").first.fill("Hello") expect(stateful.get_by_label("Text").first).to_have_value("Hello") expect( stateful.get_by_text("Result: {'range': '10', 'text': 'Hello'}") ).to_be_visible() expect( stateful.get_by_text("session_state: {'range': '10', 'text': 'Hello'}") ).to_be_visible() expect(stateful.get_by_text("Range change count: 1")).to_be_visible() expect(stateful.get_by_text("Text change count: 1")).to_be_visible() # Trigger an unrelated rerun via a Streamlit button; values remain app.get_by_text("st.button trigger").click() expect( stateful.get_by_text("Result: {'range': '10', 'text': 'Hello'}") ).to_be_visible() expect(stateful.get_by_text("session_state: {'range': '10', 'text': 'Hello'}")) expect(stateful.get_by_text("Range change count: 1")).to_be_visible() expect(stateful.get_by_text("Text change count: 1")).to_be_visible() def test_trigger_interactions(app: Page) -> None: """Test the interactions with trigger callbacks and state in the Bidi Component.""" trigger = section(app, "Trigger") expect(trigger.get_by_text("Foo count: 0")).to_be_visible() expect(trigger.get_by_text("Bar count: 0")).to_be_visible() expect(trigger.get_by_text("Result: {'foo': None, 'bar': None}")).to_be_visible() expect(trigger.get_by_text("Session state: {}")).to_be_visible() trigger.get_by_text("Trigger foo").click() expect(trigger.get_by_text("Foo count: 1")).to_be_visible() expect(trigger.get_by_text("Bar count: 0")).to_be_visible() expect(trigger.get_by_text("Result: {'foo': True, 'bar': None}")).to_be_visible() expect(trigger.get_by_text("Session state: {'foo': True}")) trigger.get_by_text("Trigger bar").click() expect(trigger.get_by_text("Foo count: 1")).to_be_visible() expect(trigger.get_by_text("Bar count: 1")).to_be_visible() expect(trigger.get_by_text("Result: {'foo': None, 'bar': True}")).to_be_visible() expect(trigger.get_by_text("Session state: {'bar': True}")) # Trigger foo again so it has a different value from bar trigger.get_by_text("Trigger foo").click() expect(trigger.get_by_text("Foo count: 2")).to_be_visible() expect(trigger.get_by_text("Bar count: 1")).to_be_visible() expect(trigger.get_by_text("Result: {'foo': True, 'bar': None}")).to_be_visible() expect(trigger.get_by_text("Session state: {'foo': True}")) trigger.get_by_text("Trigger both").click() expect(trigger.get_by_text("Foo count: 3")).to_be_visible() expect(trigger.get_by_text("Bar count: 2")).to_be_visible() expect(trigger.get_by_text("Result: {'foo': True, 'bar': True}")).to_be_visible() expect(trigger.get_by_text("Session state: {'foo': True, 'bar': True}")) # Trigger a streamlit button to ensure the trigger values in the Bidi Component get reset trigger.get_by_text("st.button trigger").click() expect(trigger.get_by_text("Foo count: 3")).to_be_visible() expect(trigger.get_by_text("Bar count: 2")).to_be_visible() expect(trigger.get_by_text("Result: {'foo': None, 'bar': None}")).to_be_visible() expect(trigger.get_by_text("Session state: {}")) def test_form_interactions_deferred_until_submit(app: Page) -> None: form = section( app, "Form context (defer state; triggers ignored by CCv2 semantics)", ) # Initial state expect(app.get_by_text("Runs: 1", exact=True)).to_be_visible() expect(form.get_by_text("Form Text changes: 0")).to_be_visible() expect(form.get_by_text("Form Clicked count: 0")).to_be_visible() # Before submitting the form, interactions should NOT trigger a rerun. form.get_by_text("Set text (Form)").click() expect(app.get_by_text("Runs: 1", exact=True)).to_be_visible() expect(form.get_by_text("Form Text changes: 0")).to_be_visible() # Triggers are disallowed in forms for CCv2; this must be a no-op. form.get_by_text("Trigger click (Form)").click() expect(app.get_by_text("Runs: 1", exact=True)).to_be_visible() expect(form.get_by_text("Form Clicked count: 0")).to_be_visible() # Also the displayed state should still be empty before submit. expect(form.get_by_text("Form session state: {}")) # Submit the form and verify rerun + updates (only stateful changes apply). click_form_button(app, "Submit Form") expect(app.get_by_text("Runs: 2", exact=True)).to_be_visible() # Trigger callback remains unchanged due to no-op in form. expect(form.get_by_text("Form Text changes: 1")).to_be_visible() expect(form.get_by_text("Form Clicked count: 0")).to_be_visible() # Session state should now contain values set by the component. expect(form.get_by_text("Form session state:")).not_to_have_text( "Form session state: {}" ) expect(form.get_by_text("Form session state:")).to_contain_text("text") def test_fragment_interactions_rerun_only_fragment(app: Page) -> None: fragment = section(app, "Fragment context (partial reruns and local counters)") # Initial state for fragments expect(app.get_by_text("Runs: 1", exact=True)).to_be_visible() expect(fragment.get_by_text("Fragment session state: {}")) expect(fragment.get_by_text("Fragment Text changes: 0")).to_be_visible() expect(fragment.get_by_text("Fragment Clicked count: 0")).to_be_visible() # Interact inside fragment: should update fragment content and callbacks, # but NOT increment global runs. fragment.get_by_text("Set text (Fragment)").click() # Fragment state updates immediately expect(fragment.get_by_text("Fragment session state:")).not_to_have_text( "Fragment session state: {}" ) expect(fragment.get_by_text("Fragment Text changes: 1")).to_be_visible() # Assert Runs remains 1 expect(app.get_by_text("Runs: 1", exact=True)).to_be_visible() fragment.get_by_text("Trigger click (Fragment)").click() # Trigger inside fragment updates fragment-local UI/state; full Runs remains 1. expect(fragment.get_by_text("Fragment Clicked count: 1")).to_be_visible() expect(app.get_by_text("Runs: 1", exact=True)).to_be_visible() def test_basic_initial_and_submission(app: Page) -> None: basic = section(app, "Basic (broad CSS + mixed state/trigger)") # Initial defaults from the component's HTML expect(basic.get_by_label("Range")).to_have_value("20") expect(basic.get_by_label("Text")).to_have_value("Text input") # Verify initial result/session_state reflects provided defaults result = basic.get_by_text("Result:") expect(result).to_contain_text("'formValues'") expect(result).to_contain_text("'range': 20") expect(result).to_contain_text("'text': 'Text input'") expect(result).to_contain_text("'clicked': None") session_state = basic.get_by_text("session_state:") expect(session_state).to_contain_text("'formValues'") expect(session_state).to_contain_text("'range': 20") expect(session_state).to_contain_text("'text': 'Text input'") expect(basic.get_by_text("Click count: 0")).to_be_visible() # Change inputs then submit the form and ensure stateful value updates basic.get_by_label("Range").fill("55") basic.get_by_label("Text").fill("Updated") basic.get_by_role("button", name="Submit form").click() result = basic.get_by_text("Result:") expect(result).to_contain_text("'clicked': True") expect(result).to_contain_text("'formValues'") expect(result).to_contain_text("'range': '55'") expect(result).to_contain_text("'text': 'Updated'") session_state = basic.get_by_text("session_state:") expect(session_state).to_contain_text("'clicked': True") expect(session_state).to_contain_text("'formValues'") expect(session_state).to_contain_text("'range': '55'") expect(session_state).to_contain_text("'text': 'Updated'") expect(basic.get_by_text("Click count: 1")).to_be_visible() def test_typing_in_component_input_does_not_trigger_global_hotkeys(app: Page) -> None: hotkey = section(app, "Global hotkey interface") # This input is component-owned HTML <input>, not a Streamlit widget. text_input = hotkey.get_by_label("Hotkey Text") runs_text = hotkey.get_by_text("Hotkey runs: 1", exact=True) hotkey.scroll_into_view_if_needed() text_input.focus() expect_global_hotkeys_not_fired(app, expected_runs=1, runs_locator=runs_text) typed = type_common_characters_into_input( text_input, after_each=lambda _ch: expect_global_hotkeys_not_fired( app, expected_runs=1, runs_locator=runs_text, ), ) expect(text_input).to_have_value(typed) def test_arrow_serialization_works(app: Page) -> None: """Verify the consolidated Arrow component renders expected content.""" arrow = section(app, "Arrow serialization") expect(arrow.get_by_text("Cols: a")).to_be_visible() expect(arrow.get_by_text('Rows: {"a": 1},{"a": 2},{"a": 3}')).to_be_visible() expect(arrow.get_by_text("Cols2: b")).to_be_visible() expect(arrow.get_by_text('Rows2: {"b": 4},{"b": 5},{"b": 6}')).to_be_visible() expect(arrow.get_by_text("Label: Hello World")).to_be_visible()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/bidi_components/basics_test.py", "license": "Apache License 2.0", "lines": 216, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/bidi_components/error_handling.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from pathlib import Path import streamlit as st st.header("Custom Components v2 - Error Handling") st.divider() with st.container(): st.subheader("Errors (intentionally broken components)") # Incorrect JS (no default export) _incorrect_js = st.components.v2.component( "incorrectJsComponent", html="""<h1>The JS is incorrect</h1>""", js=""" function Foo() { // I am some JS without a default export } """, ) _incorrect_js() # Incorrect CSS path _incorrect_css = st.components.v2.component( "incorrectCssPathComponent", html="""<h1>The CSS path is incorrect</h1>""", css=Path(__file__).parent / "incorrect_css_path.css", # type: ignore[arg-type] ) _incorrect_css()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/bidi_components/error_handling.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/bidi_components/error_handling_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page, expect def test_error_handling_messages(app: Page) -> None: expect( app.get_by_text( "BidiComponent Error: JS module does not have a default export function." ) ).to_be_visible() expect( app.get_by_text( "streamlit.errors.StreamlitAPIException: css parameter must be a string or None. " "Pass a string path or glob." ) ).to_be_visible()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/bidi_components/error_handling_test.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/bidi_components/session_state_interactions.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import streamlit as st from streamlit.components.v2.bidi_component import BidiComponentResult interactive_text_input_definition = st.components.v2.component( "interactive_text_input", html=""" <label for='txt'>Enter text:</label> <input id='txt' type='text' /> """, js=""" export default function(component) { const { setStateValue, parentElement, data, key } = component; const label = parentElement.querySelector('label'); label.innerText = data.label; const input = parentElement.querySelector('input'); // Set input value from data if changed if (input.value !== data.value) { input.value = data.value ?? ''; }; // Update value on Enter (submit) input.onkeydown = (e) => { if (e.key === 'Enter') { setStateValue('value', e.target.value); } }; } """, ) def interactive_text_input( label: str, initial_value: str, key: str ) -> BidiComponentResult: component_state = st.session_state.get(key, {}) data = { "label": label, "value": component_state.get("value", initial_value), } result = interactive_text_input_definition(data=data, key=key) return result if st.button("Make it say Hello World"): st.session_state["my_text_input"]["value"] = "Hello World" if st.button("Clear text"): st.session_state["my_text_input"]["value"] = "" user_input = interactive_text_input( "Enter something", "Initial Text", key="my_text_input" ) st.write("You entered:", user_input) if st.button("Should throw an error"): st.session_state.my_text_input.value = 12345 st.write(st.session_state)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/bidi_components/session_state_interactions.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/bidi_components/session_state_interactions_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page, expect from e2e_playwright.conftest import wait_for_app_run from e2e_playwright.shared.app_utils import ( click_button, expect_exception, expect_no_exception, get_element_by_key, ) def test_session_state_interactions_flow(app: Page) -> None: # Locate the component by its key and its internal elements component = get_element_by_key(app, "my_text_input") label = component.locator("label") input_el = component.locator("input#txt") # 1) Initial render expect(label).to_have_text("Enter something") expect(input_el).to_have_value("Initial Text") expect_no_exception(app) # 2) User submit (type + Enter) input_el.fill("Foo") input_el.press("Enter") wait_for_app_run(app) expect(input_el).to_have_value("Foo") expect_no_exception(app) # 3) Python updates flow back to the component click_button(app, "Make it say Hello World") expect(input_el).to_have_value("Hello World") # 4) Clear via Python click_button(app, "Clear text") expect(input_el).to_have_value("") # 5) Post-mount mutation error when modifying session_state click_button(app, "Should throw an error") expect_exception(app, "cannot be modified") # 6) Recovery after error (valid user submit works again) input_el.fill("Bar") input_el.press("Enter") wait_for_app_run(app) expect(input_el).to_have_value("Bar") expect_no_exception(app)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/bidi_components/session_state_interactions_test.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/components/v2/types.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shared typing utilities for the `st.components.v2` API. This module exposes common, user-facing argument types and callable signatures used by the bidirectional component API. Import these types to annotate code that constructs kwargs dictionaries for components, or when authoring wrappers/utilities around `st.components.v2.component`. The goal is to keep the public argument surface documented in one place and reusable across both the user-facing factory in `components/v2/__init__.py` and the internal implementation in `components/v2/bidi_component/main.py`. Component definitions may provide any combination of HTML, CSS, and JavaScript. If none are supplied, the component renders as an empty placeholder without raising an error. """ from __future__ import annotations from typing import TYPE_CHECKING, Any, Protocol if TYPE_CHECKING: from streamlit.components.v2.bidi_component.state import BidiComponentResult from streamlit.elements.lib.layout_utils import Height, Width from streamlit.runtime.state.common import WidgetCallback # Individual argument type aliases to make reuse ergonomic across modules. BidiComponentKey = str | None BidiComponentData = Any | None BidiComponentDefaults = dict[str, Any] | None ComponentIsolateStyles = bool class ComponentRenderer(Protocol): '''Signature of the mounting command returned by ``st.components.v2.component``. This callable mounts a bidirectional component in a Streamlit app and returns a ``BidiComponentResult`` object that exposes the component's state and trigger values. For published components, this callable is often wrapped in a user-friendly command with typed parameters and declared defaults. Parameters ---------- key : str or None An optional string to use as the unique key for the component instance. If this is omitted, an internal key is generated for the component instance based on its mounting parameters. No two Streamlit elements may have the same key. When a key is defined, the component's state is available in Session State via the key. .. note:: If you want to access this key in your component's frontend, you must pass it explicitly within the ``data`` parameter. The ``key`` parameter in ``ComponentRenderer`` is not the same as the ``key`` property in ``FrontendRendererArgs`` in the component's frontend code. The frontend key is automatically generated to be unique among all instances of all components and to avoid collisions with classes and IDs in the app's DOM. data : Any or None Data to pass to the component. This can be one of the following: - A JSON-serializable object, like ``Dict[str, str | int]`` or ``List[str]``. - An Arrow-serializable object, like ``pandas.DataFrame``. - Raw bytes. - A dictionary of JSON-serializable and Arrow-serializable objects. The dictionary's keys must be Python primitives. Because this data is sent to the frontend, it must be serializable by one of the supported serialization methods (JSON, Arrow, or raw bytes). You can't pass arbitrary Python objects. Arrow-serialization is only supported at the top level of the ``data`` parameter or one level deep in a dictionary. Raw bytes are only supported at the top level. default : dict[str, Any] or None Default state values for the component. Each key in the dictionary must correspond to a valid state attribute with an ``on_<key>_change`` callback. This callback can be empty, but must be included as a parameter when the component is mounted. Trigger values do not support manual defaults. All trigger and state values defined by an associated callback are initialized to ``None`` by default. width : "stretch", "content", or int Width of the component. This can be one of the following: - ``"stretch"`` (default): The component is wrapped in a ``<div>`` with CSS style ``width: 100%;``. - ``"content"``: The component is wrapped in a ``<div>`` with CSS style ``width: fit-content;``. - An integer specifying the width in pixels: The component is wrapped in a ``<div>`` with the specified pixel width. You are responsible for ensuring the component's inner HTML content is responsive to the ``<div>`` wrapper. height : "content", "stretch", or int Height of the component. This can be one of the following: - ``"content"`` (default): The component is wrapped in a ``<div>`` with CSS style ``height: auto;``. - ``"stretch"``: The component is wrapped in a ``<div>`` with CSS style ``height: 100%;``. - An integer specifying the height in pixels: The component is wrapped in a ``<div>`` with the specified pixel height. If the component content is larger than the specified height, scrolling is enabled. .. note:: Use scrolling containers sparingly. If you use scrolling containers, avoid heights that exceed 500 pixels. Otherwise, the scroll surface of the container might cover the majority of the screen on mobile devices, which makes it hard to scroll the rest of the app. If you want to disable scrolling for a fixed-height component, include an inner ``<div>`` wrapper in your component's HTML to control the overflow behavior. You are responsible for ensuring the component's inner HTML content is responsive to the ``<div>`` wrapper. **callbacks : Callable or None Callbacks with the naming pattern ``on_<key>_change`` for each state and trigger key. For example, if your component has a state key of ``"value"`` and a trigger key of ``"click"``, its callbacks can include ``on_value_change`` and ``on_click_change``. Only names that follow this pattern are recognized. Custom components don't currently support callbacks with arguments. Callbacks are required for any state values defined in the ``default`` parameter. Otherwise, a callback is optional. To ensure your component's result always returns the expected attributes, you can pass empty callbacks like ``lambda: None``. Returns ------- BidiComponentResult Component state object that exposes state and trigger values. Examples -------- **Example 1: Create a bidirectional text input component** If you assign a key to a mounted instance of a component, you can feed its state back into the component through the ``data`` parameter. This allows you to both read and write state values from Session State. The following example has a user-friendly wrapper around the mounting command to provide typed parameters and a clean end-user API. A couple buttons demonstrate programmatic updates to the component's state. .. code-block:: python import streamlit as st HTML = """ <label style='padding-right: 1em;' for='txt'>Enter text</label> <input id='txt' type='text' /> """ JS = """ export default function(component) { const { setStateValue, parentElement, data } = component; const label = parentElement.querySelector('label'); label.innerText = data.label; const input = parentElement.querySelector('input'); if (input.value !== data.value) { input.value = data.value ?? ''; }; input.onkeydown = (e) => { if (e.key === 'Enter') { setStateValue('value', e.target.value); } }; input.onblur = (e) => { setStateValue('value', e.target.value); }; } """ my_component = st.components.v2.component( "my_text_input", html=HTML, js=JS, ) def my_component_wrapper( label, *, default="", key=None, on_change=lambda: None ): component_state = st.session_state.get(key, {}) value = component_state.get("value", default) data = {"label": label, "value": value} result = my_component( data=data, default={"value": value}, key=key, on_value_change=on_change, ) return result st.title("My custom component") if st.button("Hello World"): st.session_state["my_text_input_instance"]["value"] = "Hello World" if st.button("Clear text"): st.session_state["my_text_input_instance"]["value"] = "" result = my_component_wrapper( "Enter something", default="I love Streamlit!", key="my_text_input_instance", ) st.write("Result:", result) st.write("Session state:", st.session_state) .. output:: https://doc-components-text-input.streamlit.app/ height: 600px **Example 2: Add Tailwind CSS to a component** You can use the ``isolate_styles`` parameter in ``st.components.v2.component`` to disable shadow DOM isolation and apply global styles like Tailwind CSS to your component. The following example creates a simple button styled with Tailwind CSS. This example also demonstrates using different keys to mount multiple instances of the same component in one app. .. code-block:: python import streamlit as st with open("tailwind.js", "r") as f: TAILWIND_SCRIPT = f.read() HTML = """ <button class="bg-blue-500 hover:bg-blue-700 text-white py-1 px-3 rounded"> Click me! </button> """ JS = ( TAILWIND_SCRIPT + """ export default function(component) { const { setTriggerValue, parentElement } = component; const button = parentElement.querySelector('button'); button.onclick = () => { setTriggerValue('clicked', true); }; } """ ) my_component = st.components.v2.component( "my_tailwind_button", html=HTML, js=JS, isolate_styles=False, ) result_1 = my_component(on_clicked_change=lambda: None, key="one") result_1 result_2 = my_component(on_clicked_change=lambda: None, key="two") result_2 .. output:: https://doc-components-tailwind-button.streamlit.app/ height: 350px ''' def __call__( self, *, key: BidiComponentKey = None, data: BidiComponentData = None, default: BidiComponentDefaults = None, width: Width = "stretch", height: Height = "content", **on_callbacks: WidgetCallback | None, ) -> BidiComponentResult: ... __all__ = [ "BidiComponentData", "BidiComponentDefaults", "BidiComponentKey", "ComponentIsolateStyles", "ComponentRenderer", ]
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/types.py", "license": "Apache License 2.0", "lines": 253, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_api_paths.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import MagicMock, patch import pytest from streamlit.components.v2 import component as component_api from streamlit.components.v2.manifest_scanner import ComponentConfig, ComponentManifest from streamlit.errors import StreamlitAPIException, StreamlitComponentRegistryError from streamlit.runtime import Runtime if TYPE_CHECKING: from pathlib import Path def _with_runtime_manager(manager): """Create a patcher for the Runtime to inject a mock component manager.""" return patch.object( Runtime, "instance", return_value=MagicMock(bidi_component_registry=manager) ) def test_api_accepts_paths_inside_asset_dir(tmp_path: Path) -> None: """API should accept js/css paths that resolve inside manifest-declared asset_dir.""" from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() manager.clear() # Package with asset_dir package_root = tmp_path / "pkg" asset_dir = package_root / "assets" asset_dir.mkdir(parents=True) js_file = asset_dir / "index-abc.js" css_file = asset_dir / "index.css" js_file.write_text("export default function(){}") css_file.write_text(".x{}") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) # Sanity: asset root is registered assert manager.get_component_asset_root("pkg.slider") is not None with ( patch.object(Runtime, "exists", return_value=True), _with_runtime_manager(manager), ): # Provide asset-dir-relative paths (relative to asset_dir root) comp = component_api(name="pkg.slider", js="index-abc.js", css="index.css") assert callable(comp) def test_api_rejects_paths_outside_asset_dir(tmp_path: Path) -> None: """API should reject js/css paths outside the manifest asset_dir.""" from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() manager.clear() package_root = tmp_path / "pkg" asset_dir = package_root / "assets" asset_dir.mkdir(parents=True) outside_file = tmp_path / "outside.js" outside_file.write_text("export default function(){}") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) with ( patch.object(Runtime, "exists", return_value=True), _with_runtime_manager(manager), ): with pytest.raises(StreamlitComponentRegistryError): component_api(name="pkg.slider", js=str(outside_file)) def test_api_glob_expands_to_single_file(tmp_path: Path) -> None: """API should expand globs inside asset_dir to exactly one file.""" from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() manager.clear() package_root = tmp_path / "pkg" asset_dir = package_root / "assets" asset_dir.mkdir(parents=True) (asset_dir / "index-1.js").write_text("export default function(){}") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) with ( patch.object(Runtime, "exists", return_value=True), _with_runtime_manager(manager), ): comp = component_api(name="pkg.slider", js="index-*.js") assert callable(comp) def test_api_rejects_absolute_paths(tmp_path: Path) -> None: """API must reject absolute file paths for js/css inputs.""" from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() manager.clear() package_root = tmp_path / "pkg" asset_dir = package_root / "assets" asset_dir.mkdir(parents=True) js_file = asset_dir / "index.js" js_file.write_text("export default function(){}") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) abs_js = str(js_file.resolve()) abs_css = str((asset_dir / "index.css").resolve()) (asset_dir / "index.css").write_text(".x{}") with ( patch.object(Runtime, "exists", return_value=True), _with_runtime_manager(manager), ): with pytest.raises(StreamlitComponentRegistryError): component_api(name="pkg.slider", js=abs_js) with pytest.raises(StreamlitComponentRegistryError): component_api(name="pkg.slider", css=abs_css) def test_api_errors_when_missing_manifest_registration(tmp_path: Path) -> None: """If component is not declared in pyproject.toml, file-backed API must error.""" from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() manager.clear() # No manifest registration for manager package_root = tmp_path / "pkg" asset_dir = package_root / "assets" asset_dir.mkdir(parents=True) js_file = asset_dir / "index.js" js_file.write_text("export default function(){}") with ( patch.object(Runtime, "exists", return_value=True), _with_runtime_manager(manager), ): with pytest.raises(StreamlitAPIException): component_api(name="pkg.slider", js=str(js_file)) def test_api_rejects_non_string_types(tmp_path: Path) -> None: """Reject non-string, non-None values for js/css parameters.""" from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() manager.clear() package_root = tmp_path / "pkg" asset_dir = package_root / "assets" asset_dir.mkdir(parents=True) (asset_dir / "index.js").write_text("export default function(){}") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) with ( patch.object(Runtime, "exists", return_value=True), _with_runtime_manager(manager), ): with pytest.raises(StreamlitAPIException): component_api(name="pkg.slider", js=123) # type: ignore[arg-type] with pytest.raises(StreamlitAPIException): component_api(name="pkg.slider", css=["invalid"]) # type: ignore[arg-type]
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_component_api_paths.py", "license": "Apache License 2.0", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/components/v2/test_default_state.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration tests for the `default` parameter in Components V2.""" from __future__ import annotations from unittest.mock import MagicMock, patch import pytest from streamlit.components.v2 import component from streamlit.components.v2.component_manager import BidiComponentManager from streamlit.errors import StreamlitAPIException from streamlit.runtime import Runtime from tests.delta_generator_test_case import DeltaGeneratorTestCase class DefaultStateIntegrationTest(DeltaGeneratorTestCase): """Integration tests for `default` using the public component API.""" def setUp(self) -> None: """Set up a fresh component manager patched into the Runtime singleton.""" super().setUp() self.mock_component_manager = BidiComponentManager() self.runtime_patcher = patch.object( Runtime, "instance", return_value=MagicMock() ) self.mock_runtime = self.runtime_patcher.start() self.mock_runtime.return_value.bidi_component_registry = ( self.mock_component_manager ) def tearDown(self) -> None: """Tear down the runtime patcher.""" super().tearDown() self.runtime_patcher.stop() def test_component_with_default_basic(self) -> None: """Test basic `default` functionality with the public API.""" # Declare a component my_component = component( "test_component", js="console.log('test');", ) # Create mock callbacks on_value_change = MagicMock() on_enabled_change = MagicMock() # Use the component with default result = my_component( default={ "value": 42, "enabled": False, }, on_value_change=on_value_change, on_enabled_change=on_enabled_change, ) # Verify defaults are applied assert result["value"] == 42 assert result["enabled"] is False def test_component_default_validation(self) -> None: """Test that `default` key validation works with the public API.""" # Declare a component my_component = component( "validation_test_component", js="console.log('validation test');", ) # Create callback for only one state on_valid_change = MagicMock() # Try to use invalid default with pytest.raises(StreamlitAPIException) as exc_info: my_component( default={ "valid": "this is ok", "invalid": "this should fail", }, on_valid_change=on_valid_change, ) # Verify the error message error_message = str(exc_info.value) assert "invalid" in error_message assert "not a valid state name" in error_message def test_component_default_with_data(self) -> None: """Test that `default` works correctly with the `data` parameter.""" # Declare a component my_component = component( "data_and_defaults_component", js="console.log('data and defaults');", ) # Create callbacks on_selection_change = MagicMock() on_mode_change = MagicMock() # Use both data and default result = my_component( data={"items": ["a", "b", "c"]}, default={ "selection": [], "mode": "single", }, on_selection_change=on_selection_change, on_mode_change=on_mode_change, ) # Verify defaults are applied assert result["selection"] == [] assert result["mode"] == "single" # Verify the proto contains both data and component setup delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name.endswith( "data_and_defaults_component" ) def test_component_default_complex_types(self) -> None: """Test `default` with complex data types like lists and dicts.""" # Declare a component my_component = component( "complex_types_component", js="console.log('complex types');", ) # Create callbacks on_items_change = MagicMock() on_config_change = MagicMock() # Complex default values default_items = [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] default_config = { "theme": "dark", "settings": {"auto_save": True, "timeout": 30}, } # Use the component result = my_component( default={ "items": default_items, "config": default_config, }, on_items_change=on_items_change, on_config_change=on_config_change, ) # Verify complex defaults are preserved assert result["items"] == default_items assert result["config"] == default_config assert result["config"]["settings"]["auto_save"] is True def test_component_default_none_values(self) -> None: """Test `default` with None values using the public API.""" # Declare a component my_component = component( "none_values_component", js="console.log('none values');", ) # Create callback on_nullable_change = MagicMock() # Use None as default value result = my_component( default={"nullable": None}, on_nullable_change=on_nullable_change, ) # Verify None is properly handled assert result["nullable"] is None
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_default_state.py", "license": "Apache License 2.0", "lines": 157, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/components/v2/bidi_component/constants.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Final INTERNAL_COMPONENT_NAME: Final[str] = "bidi_component" # Shared constant that delimits the base widget id from the event suffix. # This value **must** stay in sync with its TypeScript counterpart defined in # `frontend/lib/src/components/widgets/BidiComponent/constants.ts`. EVENT_DELIM: Final[str] = "__" # Shared constant that is used to identify ArrowReference objects in the data structure. # This value **must** stay in sync with its TypeScript counterpart defined in # `frontend/lib/src/components/widgets/BidiComponent/constants.ts`. ARROW_REF_KEY: Final[str] = "__streamlit_arrow_ref__"
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/bidi_component/constants.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/bidi_component/main.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import json from collections.abc import Mapping from typing import TYPE_CHECKING, Any, cast from streamlit.components.v2.bidi_component.constants import ( EVENT_DELIM, INTERNAL_COMPONENT_NAME, ) from streamlit.components.v2.bidi_component.serialization import ( BidiComponentSerde, deserialize_trigger_list, serialize_mixed_data, ) from streamlit.components.v2.bidi_component.state import ( BidiComponentResult, unwrap_component_state, ) from streamlit.components.v2.presentation import make_bidi_component_presenter from streamlit.dataframe_util import ( DataFormat, convert_anything_to_arrow_bytes, determine_data_format, ) from streamlit.elements.lib.form_utils import current_form_id from streamlit.elements.lib.layout_utils import ( Height, LayoutConfig, Width, validate_width, ) from streamlit.elements.lib.policies import check_cache_replay_rules from streamlit.elements.lib.utils import compute_and_register_element_id, to_key from streamlit.errors import ( BidiComponentInvalidCallbackNameError, BidiComponentInvalidDefaultKeyError, BidiComponentInvalidIdError, BidiComponentUnserializableDataError, ) from streamlit.proto.ArrowData_pb2 import ArrowData as ArrowDataProto from streamlit.proto.BidiComponent_pb2 import BidiComponent as BidiComponentProto from streamlit.proto.BidiComponent_pb2 import MixedData as MixedDataProto from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx from streamlit.runtime.state import register_widget from streamlit.util import calc_md5 if TYPE_CHECKING: from streamlit.components.v2.types import ( BidiComponentData, BidiComponentDefaults, BidiComponentKey, ComponentIsolateStyles, ) if TYPE_CHECKING: # Define DeltaGenerator for type checking the dg property from streamlit.delta_generator import DeltaGenerator from streamlit.runtime.state.common import WidgetCallback def _make_trigger_id(base: str, event: str) -> str: """Construct the per-event *trigger widget* identifier. The widget ID for a trigger is derived from the *base* component ID plus an *event* name. We join those two parts with :py:const:`EVENT_DELIM` and perform a couple of validations so that downstream logic can always split the identifier unambiguously. Trigger widgets are marked as internal by prefixing with an internal key prefix, so they won't be exposed in `st.session_state` to end users. Parameters ---------- base The unique, framework-assigned ID of the component instance. event The event name as provided by either the frontend or the developer (e.g., "click", "change"). Returns ------- str The composite widget ID in the form ``"$$STREAMLIT_INTERNAL_KEY_{base}__{event}"`` where ``__`` is the delimiter. Raises ------ StreamlitAPIException If either `base` or `event` already contains the delimiter sequence. """ from streamlit.runtime.state.session_state import STREAMLIT_INTERNAL_KEY_PREFIX if EVENT_DELIM in base: raise BidiComponentInvalidIdError("base", EVENT_DELIM) if EVENT_DELIM in event: raise BidiComponentInvalidIdError("event", EVENT_DELIM) return f"{STREAMLIT_INTERNAL_KEY_PREFIX}_{base}{EVENT_DELIM}{event}" class BidiComponentMixin: """Mixin class for the bidi_component DeltaGenerator method.""" def _canonicalize_json_for_identity(self, payload: str) -> str: """Return a deterministic JSON string for identity comparisons. Payloads that cannot be parsed (or re-serialized) are returned as-is to avoid mutating developer data. """ if not payload: return payload try: parsed = json.loads(payload) except (TypeError, ValueError): return payload try: return json.dumps(parsed, sort_keys=True) except (TypeError, ValueError): return payload def _canonical_json_digest_for_identity(self, payload: str) -> str: """Return the hash of the canonicalized JSON payload for identity use. Hashing keeps the kwargs passed to ``compute_and_register_element_id`` small even when the JSON payload is very large, while still changing the identity whenever the canonical JSON content changes. """ canonical = self._canonicalize_json_for_identity(payload) return calc_md5(canonical) def _build_bidi_identity_kwargs( self, *, component_name: str, isolate_styles: bool, width: Width, height: Height, proto: BidiComponentProto, data: BidiComponentData = None, default: BidiComponentDefaults = None, ) -> dict[str, Any]: """Build deterministic identity kwargs for ID computation. Construct a stable mapping of identity-relevant properties for ``compute_and_register_element_id``. This includes structural properties (name, style isolation, layout), default state values, and an explicit, typed handling of the ``BidiComponent`` ``oneof data`` field to ensure unkeyed components change identity when their serialized payload or defaults change. Parameters ---------- component_name : str The registered component name. isolate_styles : bool Whether the component styles are rendered in a Shadow DOM. width : Width Desired width configuration passed to the component. height : Height Desired height configuration passed to the component. proto : BidiComponentProto The populated component protobuf. Its ``data`` oneof determines which serialized payload (JSON, Arrow, bytes, or Mixed) contributes to identity. data : BidiComponentData, optional The raw data passed to the component. Used to optimize identity calculation for JSON payloads by avoiding a parse/serialize cycle. When omitted, the helper falls back to canonicalizing the JSON content stored on the protobuf. default : BidiComponentDefaults, optional The default state mapping for the component instance. Defaults are included in the identity for unkeyed components so that changing default values produces a new backend identity. When a user key is provided with ``key_as_main_identity=True``, these defaults are ignored by :func:`compute_and_register_element_id`. Returns ------- dict[str, Any] A mapping of deterministic values to be forwarded into ``compute_and_register_element_id``. Raises ------ RuntimeError If an unhandled ``oneof data`` variant is encountered (guards against adding new fields without updating identity computation). """ identity: dict[str, Any] = { "component_name": component_name, "isolate_styles": isolate_styles, "width": width, "height": height, "default": default, } data_field = proto.WhichOneof("data") if data_field is None: return identity if data_field == "json": # Canonicalize only for identity so unkeyed widgets don't churn when # dict insertion order changes. # # Optimization: Use raw `data` if available to avoid the overhead of # parsing `proto.json` back into a dict. canonical_digest = None if data is not None: try: canonical = json.dumps(data, sort_keys=True) canonical_digest = calc_md5(canonical) except (TypeError, ValueError): # Fallback to existing logic if direct dump fails pass if canonical_digest is None: canonical_digest = self._canonical_json_digest_for_identity(proto.json) identity["json"] = canonical_digest elif data_field == "arrow_data": # Hash large payloads instead of shoving raw bytes through the ID # hasher for performance. identity["arrow_data"] = calc_md5(proto.arrow_data.data) elif data_field == "bytes": # Same story for arbitrary bytes payloads: content-address the data # so identity changes track real mutations without re-hashing the # whole blob every run. identity["bytes"] = calc_md5(proto.bytes) elif data_field == "mixed": mixed: MixedDataProto = proto.mixed # Add the JSON content of the MixedData to the identity. identity["mixed_json"] = self._canonical_json_digest_for_identity( mixed.json ) # Add the sorted content-addressed ref IDs of the Arrow blobs to the identity. # Unlike other data types where we include actual bytes, here we only include # the blob keys. This is sufficient because keys are MD5 hashes of the blob # content (content-addressed), so identical content produces identical keys. identity["mixed_arrow_blobs"] = ",".join(sorted(mixed.arrow_blobs.keys())) else: raise RuntimeError( f"Unhandled BidiComponent.data oneof field: {data_field}" ) return identity @gather_metrics("_bidi_component") def _bidi_component( self, component_name: str, key: BidiComponentKey = None, isolate_styles: ComponentIsolateStyles = True, data: BidiComponentData = None, default: BidiComponentDefaults = None, width: Width = "stretch", height: Height = "content", **kwargs: WidgetCallback | None, ) -> BidiComponentResult: """Add a bidirectional component instance to the app. This method uses a component that has already been registered with the application. Parameters ---------- component_name The name of the registered component to use. The component's HTML, CSS, and JavaScript will be loaded from the registry. key An optional string to use as the unique key for the component. If this is omitted, a key will be generated based on the component's execution sequence. isolate_styles Whether to sandbox the component's styles in a shadow root. Defaults to True. data Data to pass to the component. This can be any JSON-serializable data, or a pandas DataFrame, NumPy array, or other dataframe-like object that can be serialized to Arrow. default A dictionary of default values for the component's state properties. These defaults are applied only when the state key doesn't exist in session state. Keys must correspond to valid state names (those with `on_*_change` callbacks). Trigger values do not support defaults. width The desired width of the component. This can be one of "stretch", "content", or a number of pixels. height The desired height of the component. This can be one of "stretch", "content", or a number of pixels. **kwargs Keyword arguments to pass to the component. Callbacks can be passed here, with the naming convention `on_{event_name}_change`. Returns ------- BidiComponentResult A dictionary-like object that holds the component's state and trigger values. Raises ------ ValueError If the component name is not found in the registry. StreamlitAPIException If the component does not have the required JavaScript or HTML content, or if the provided data cannot be serialized. """ check_cache_replay_rules() key = to_key(key) ctx = get_script_run_ctx() if ctx is None: # Create an empty state with the default value and return it return BidiComponentResult({}, {}) # Get the component definition from the registry from streamlit.runtime import Runtime registry = Runtime.instance().bidi_component_registry component_def = registry.get(component_name) if component_def is None: raise ValueError(f"Component '{component_name}' is not registered") # ------------------------------------------------------------------ # 1. Parse user-supplied callbacks # ------------------------------------------------------------------ # Event-specific callbacks follow the pattern ``on_<event>_change``. # We deliberately *do not* support the legacy generic ``on_change`` # or ``on_<event>`` forms. callbacks_by_event: dict[str, WidgetCallback] = {} for kwarg_key, kwarg_value in list(kwargs.items()): if not callable(kwarg_value): continue if kwarg_key.startswith("on_") and kwarg_key.endswith("_change"): # Preferred pattern: on_<event>_change event_name = kwarg_key[3:-7] # strip prefix + suffix else: # Not an event callback we recognize - skip. continue if not event_name or event_name == "_": raise BidiComponentInvalidCallbackNameError(kwarg_key) callbacks_by_event[event_name] = kwarg_value # ------------------------------------------------------------------ # 2. Validate default keys against registered callbacks # ------------------------------------------------------------------ if default is not None: for state_key in default: if state_key not in callbacks_by_event: raise BidiComponentInvalidDefaultKeyError( state_key, list(callbacks_by_event.keys()) ) # Set up the component proto bidi_component_proto = BidiComponentProto() bidi_component_proto.component_name = component_name bidi_component_proto.isolate_styles = isolate_styles bidi_component_proto.js_content = component_def.js_content or "" bidi_component_proto.js_source_path = component_def.js_url or "" bidi_component_proto.html_content = component_def.html_content or "" bidi_component_proto.css_content = component_def.css_content or "" bidi_component_proto.css_source_path = component_def.css_url or "" validate_width(width, allow_content=True) layout_config = LayoutConfig(width=width, height=height) if data is not None: try: # 1. Raw byte payloads - forward as-is. if isinstance(data, (bytes, bytearray)): bidi_component_proto.bytes = bytes(data) # 2. Mapping-like structures (e.g. plain dict) - check for mixed data. elif isinstance(data, (Mapping, list, tuple)): serialize_mixed_data(data, bidi_component_proto) # 3. Dataframe-like structures - attempt Arrow serialization. else: data_format = determine_data_format(data) if data_format != DataFormat.UNKNOWN: arrow_bytes = convert_anything_to_arrow_bytes(data) arrow_data_proto = ArrowDataProto() arrow_data_proto.data = arrow_bytes bidi_component_proto.arrow_data.CopyFrom(arrow_data_proto) else: # Fallback to JSON. bidi_component_proto.json = json.dumps(data) except Exception: # As a last resort attempt JSON serialization so that we don't # silently drop developer data. try: bidi_component_proto.json = json.dumps(data) except Exception: raise BidiComponentUnserializableDataError() bidi_component_proto.form_id = current_form_id(self.dg) # Build identity kwargs for the component instance now that the proto is # populated. identity_kwargs = self._build_bidi_identity_kwargs( component_name=component_name, isolate_styles=isolate_styles, width=width, height=height, proto=bidi_component_proto, data=data, default=default, ) # Compute a unique ID for this component instance now that the proto is # populated. computed_id = compute_and_register_element_id( "bidi_component", user_key=key, key_as_main_identity=True, dg=self.dg, **identity_kwargs, ) bidi_component_proto.id = computed_id # Instantiate the Serde for this component instance serde = BidiComponentSerde(default=default) # ------------------------------------------------------------------ # 3. Prepare IDs and register widgets # ------------------------------------------------------------------ # Compute trigger aggregator id from the base id def _make_trigger_aggregator_id(base: str) -> str: return _make_trigger_id(base, "events") aggregator_id = _make_trigger_aggregator_id(computed_id) # With generalized runtime dispatch, we can attach per-key callbacks # directly to the state widget by passing the callbacks mapping. # We also register a presenter to shape the user-visible session_state. # Allowed state keys are the ones that have callbacks registered. allowed_state_keys = ( set(callbacks_by_event.keys()) if callbacks_by_event else None ) presenter = make_bidi_component_presenter( aggregator_id, computed_id, allowed_state_keys, ) component_state = register_widget( bidi_component_proto.id, deserializer=serde.deserialize, serializer=serde.serialize, ctx=ctx, callbacks=callbacks_by_event or None, value_type="json_value", presenter=presenter, ) # ------------------------------------------------------------------ # 4. Register a single *trigger aggregator* widget # ------------------------------------------------------------------ trigger_vals: dict[str, Any] = {} trig_state = register_widget( aggregator_id, deserializer=deserialize_trigger_list, # always returns list or None serializer=lambda v: json.dumps(v), # send dict as JSON ctx=ctx, callbacks=callbacks_by_event or None, value_type="json_trigger_value", ) # Surface per-event trigger values derived from the aggregator payload list. payloads: list[object] = trig_state.value or [] event_to_value: dict[str, Any] = {} for payload in payloads: if isinstance(payload, dict): ev = payload.get("event") if isinstance(ev, str): event_to_value[ev] = payload.get("value") for evt_name in callbacks_by_event: trigger_vals[evt_name] = event_to_value.get(evt_name) # Note: We intentionally do not inspect SessionState for additional # trigger widget IDs here because doing so can raise KeyErrors when # widgets are freshly registered but their values haven't been # populated yet. Only the triggers explicitly registered above are # included in the result object. # ------------------------------------------------------------------ # 5. Enqueue proto and assemble the result object # ------------------------------------------------------------------ self.dg._enqueue( INTERNAL_COMPONENT_NAME, bidi_component_proto, layout_config=layout_config, ) state_vals = unwrap_component_state(component_state.value) return BidiComponentResult(state_vals, trigger_vals) @property def dg(self) -> DeltaGenerator: """Get our DeltaGenerator.""" return cast("DeltaGenerator", self)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/bidi_component/main.py", "license": "Apache License 2.0", "lines": 460, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/bidi_component/serialization.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import json from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast from streamlit.components.v2.bidi_component.constants import ARROW_REF_KEY from streamlit.dataframe_util import convert_anything_to_arrow_bytes, is_dataframe_like from streamlit.logger import get_logger from streamlit.proto.BidiComponent_pb2 import BidiComponent as BidiComponentProto from streamlit.proto.BidiComponent_pb2 import MixedData as MixedDataProto from streamlit.util import AttributeDictionary, calc_md5 if TYPE_CHECKING: from streamlit.components.v2.bidi_component.state import BidiComponentState _LOGGER = get_logger(__name__) def _extract_dataframes_from_dict( data: dict[str, Any], arrow_blobs: dict[str, bytes] | None = None ) -> dict[str, Any]: """Extract dataframe-like objects from a dictionary and replace them with placeholders. This function traverses the first level of a dictionary, detects any dataframe-like objects, stores their Arrow bytes representation in the `arrow_blobs` dictionary, and replaces them with JSON-serializable placeholder objects. Parameters ---------- data The dictionary to process. Only the first level is checked for dataframe-like objects. arrow_blobs The dictionary to store the extracted Arrow bytes in, keyed by a unique reference ID. Returns ------- dict[str, Any] A new dictionary with dataframe-like objects replaced by placeholders. """ if arrow_blobs is None: arrow_blobs = {} processed_data = {} for key, value in data.items(): if is_dataframe_like(value): # This is a dataframe-like object, serialize it to Arrow try: arrow_bytes = convert_anything_to_arrow_bytes(value) # Use deterministic, content-addressed ref IDs so placeholders # are stable for identical content on each run. This also provides # natural deduplication - identical DataFrames share a single blob. ref_id = calc_md5(arrow_bytes) arrow_blobs[ref_id] = arrow_bytes processed_data[key] = {ARROW_REF_KEY: ref_id} except Exception as e: # If Arrow serialization fails, keep the original value for JSON # serialization attempt downstream. _LOGGER.debug( "Arrow serialization failed for key %r, keeping original value: %s", key, e, ) processed_data[key] = value else: # Not dataframe-like, keep as-is processed_data[key] = value return processed_data def serialize_mixed_data(data: Any, bidi_component_proto: BidiComponentProto) -> None: """Serialize mixed data with automatic dataframe detection into a protobuf message. This function detects dataframe-like objects in the first level of a dictionary, extracts them into separate Arrow blobs, and populates a `MixedDataProto` protobuf message for efficient serialization. Parameters ---------- data The data structure to serialize. If it is a dictionary, its first level will be scanned for dataframe-like objects. bidi_component_proto The protobuf message to populate with the serialized data. """ arrow_blobs: dict[str, bytes] = {} # Only process dictionaries for automatic dataframe detection if isinstance(data, dict): processed_data = _extract_dataframes_from_dict(data, arrow_blobs) else: # For non-dict data (lists, tuples, etc.), pass through as-is # We don't automatically detect dataframes in these structures processed_data = data if arrow_blobs: # We have dataframes, use mixed data serialization mixed_proto = MixedDataProto() try: mixed_proto.json = json.dumps(processed_data) except TypeError: # If JSON serialization fails (e.g., due to undetected dataframes), # fall back to string representation mixed_proto.json = json.dumps(str(processed_data)) # Add Arrow blobs to the protobuf for ref_id, arrow_bytes in arrow_blobs.items(): mixed_proto.arrow_blobs[ref_id].data = arrow_bytes bidi_component_proto.mixed.CopyFrom(mixed_proto) else: # No dataframes found, use regular JSON serialization try: bidi_component_proto.json = json.dumps(processed_data) except TypeError: # If JSON serialization fails (e.g., due to dataframes in lists/tuples), # fall back to string representation bidi_component_proto.json = json.dumps(str(processed_data)) def handle_deserialize(s: str | None) -> Any: """Deserialize a JSON string, returning the string itself if it's not valid JSON. Parameters ---------- s The string to deserialize. Returns ------- Any The deserialized JSON object, or the original string if parsing fails. Returns `None` if the input is `None`. """ if s is None: return None try: return json.loads(s) except json.JSONDecodeError: return s def deserialize_trigger_list(s: str | None) -> list[Any] | None: """Deserialize trigger aggregator payloads as a list. For bidirectional components, the frontend always sends a JSON array of payload objects. This deserializer normalizes older or singular payloads into a list while preserving ``None`` for cleared values. Parameters ---------- s The JSON string to deserialize, hopefully representing a list of payloads. Returns ------- list[Any] or None A list of payloads, or `None` if the input was `None`. """ value = handle_deserialize(s) if value is None: return None if isinstance(value, list): return value return [value] @dataclass class BidiComponentSerde: """Serialization and deserialization logic for a bidirectional component. This class handles the conversion of component state between the frontend (JSON strings) and the backend (Python objects). The canonical shape is a flat mapping of state keys to values. Parameters ---------- default A dictionary of default values to be applied to the state when deserializing, if the corresponding keys are not already present. """ default: dict[str, Any] | None = None def deserialize(self, ui_value: str | dict[str, Any] | None) -> BidiComponentState: """Deserialize the component's state from a frontend value. Parameters ---------- ui_value The value received from the frontend, which can be a JSON string, a dictionary, or `None`. Returns ------- BidiComponentState The deserialized state as a flat mapping. """ # Normalize the incoming JSON payload into a dict. Any failure to decode # (or an unexpected non-mapping structure) results in an empty mapping # so that the returned type adheres to :class:`BidiComponentState`. deserialized_value: dict[str, Any] if isinstance(ui_value, dict): deserialized_value = ui_value elif isinstance(ui_value, str): try: parsed = json.loads(ui_value) deserialized_value = parsed if isinstance(parsed, dict) else {} except (json.JSONDecodeError, TypeError) as e: _LOGGER.warning( "Failed to deserialize component state from frontend: %s", e, exc_info=e, ) deserialized_value = {} else: deserialized_value = {} # Apply default values for keys that don't exist in the current state if self.default is not None: for default_key, default_value in self.default.items(): if default_key not in deserialized_value: deserialized_value[default_key] = default_value state: BidiComponentState = cast( "BidiComponentState", AttributeDictionary(deserialized_value) ) return state def serialize(self, value: Any) -> str: """Serialize the component's state into a JSON string for the frontend. Parameters ---------- value The component state to serialize. Returns ------- str A JSON string representation of the value. """ return json.dumps(value)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/bidi_component/serialization.py", "license": "Apache License 2.0", "lines": 220, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/bidi_component/state.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Any, TypedDict from streamlit.util import AttributeDictionary class BidiComponentState(TypedDict, total=False): """ The schema for the state of a bidirectional component. The state is a flat dictionary-like object (key -> value) that supports both key and attribute notation via :class:`AttributeDictionary`. """ # Flat mapping of state key -> value # (kept empty to reflect open set of keys) class BidiComponentResult(AttributeDictionary): """The schema for the custom component result object. The custom component result object is a dictionary-like object that supports both key and attribute notation. It contains all of the component's state and trigger values. Attributes ---------- <state_keys> : Any All state values from the component. State values are persistent across app reruns until explicitly changed. You can have multiple state keys as attributes. <trigger_keys> : Any All trigger values from the component. Trigger values are transient and reset to ``None`` after one script run. You can have multiple trigger keys as attributes. """ def __init__( self, state_vals: dict[str, Any] | None = None, trigger_vals: dict[str, Any] | None = None, ) -> None: """Initialize a BidiComponentResult. Parameters ---------- state_vals : dict[str, Any] or None A dictionary of state values from the component. trigger_vals : dict[str, Any] or None A dictionary of trigger values from the component. """ if state_vals is None: state_vals = {} if trigger_vals is None: trigger_vals = {} super().__init__( { # The order here matters, because all stateful values will # always be returned, but trigger values may be transient. This # mirrors presentation behavior in # `make_bidi_component_presenter`. **trigger_vals, **state_vals, } ) def unwrap_component_state(raw_state: Any) -> dict[str, Any]: """Return flat mapping when given a dict; otherwise, empty dict. The new canonical state is flat, so this is effectively an identity for dict inputs and a guard for other types. """ return dict(raw_state) if isinstance(raw_state, dict) else {}
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/bidi_component/state.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/presentation.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Any, TypedDict, cast from typing_extensions import Self from streamlit.errors import StreamlitAPIException from streamlit.logger import get_logger from streamlit.runtime.scriptrunner import get_script_run_ctx if TYPE_CHECKING: from streamlit.runtime.state import SessionState from streamlit.runtime.state.common import WidgetValuePresenter _LOGGER = get_logger(__name__) class _TriggerPayload(TypedDict, total=False): event: str value: object def make_bidi_component_presenter( aggregator_id: str, component_id: str | None = None, allowed_state_keys: set[str] | None = None, ) -> WidgetValuePresenter: """Return a presenter that merges trigger events into CCv2 state. This function returns a callable that takes a component's persistent state value and the current `SessionState` instance, and returns the user-visible value that should appear in `st.session_state`. The presenter is side-effect-free and does not mutate stored state or callback behavior. It is intended to be attached to the persistent state widget via the generic `presenter` hook. Parameters ---------- aggregator_id The ID of the trigger aggregator widget that holds the event payloads. Returns ------- WidgetValuePresenter A callable that merges the trigger event values into the component's base state for presentation in `st.session_state`. """ def _present(base_value: object, session_state: SessionState) -> object: def _check_modification(k: str) -> None: ctx = get_script_run_ctx() if ctx is not None and component_id is not None: user_key = session_state._key_id_mapper.get_key_from_id(component_id) if ( component_id in ctx.widget_ids_this_run or user_key in ctx.form_ids_this_run ): raise StreamlitAPIException( f"`st.session_state.{user_key}.{k}` cannot be modified after the component" f" with key `{user_key}` is instantiated." ) # Base state must be a flat mapping; otherwise, present as-is. base_map: dict[str, object] | None = None if isinstance(base_value, dict): base_map = cast("dict[str, object]", base_value) if base_map is not None: # Read the trigger aggregator payloads if present try: agg_meta = session_state._new_widget_state.widget_metadata.get( aggregator_id ) if agg_meta is None or agg_meta.value_type != "json_trigger_value": return base_value try: agg_payloads_obj = session_state._new_widget_state[aggregator_id] except KeyError: agg_payloads_obj = None payloads_list: list[_TriggerPayload] | None if agg_payloads_obj is None: payloads_list = None elif isinstance(agg_payloads_obj, list): # Filter and cast to the expected payload type shape payloads_list = [ cast("_TriggerPayload", p) for p in agg_payloads_obj if isinstance(p, dict) ] elif isinstance(agg_payloads_obj, dict): payloads_list = [cast("_TriggerPayload", agg_payloads_obj)] else: payloads_list = None event_to_val: dict[str, object] = {} if payloads_list is not None: for payload in payloads_list: ev = payload.get("event") if isinstance(ev, str): event_to_val[ev] = payload.get("value") # Merge triggers into a flat view: triggers first, then base flat: dict[str, object] = dict(event_to_val) flat.update(base_map) # Return a write-through dict that updates the underlying # component state when users assign nested keys via # st.session_state[component_user_key][name] = value. Using a # dict subclass ensures pretty-printing and JSON serialization # behave as expected for st.write and logs. class _WriteThrough(dict[str, object]): # noqa: FURB189 def __init__(self, data: dict[str, object]) -> None: super().__init__(data) def __getattr__(self, name: str) -> object: return self.get(name) def __setattr__(self, name: str, value: object) -> None: if name.startswith(("__", "_")): return super().__setattr__(name, value) self[name] = value return None def __deepcopy__(self, memo: dict[int, Any]) -> Self: # This object is a proxy to the real state. Don't copy it. memo[id(self)] = self return self def __setitem__(self, k: str, v: object) -> None: _check_modification(k) if ( allowed_state_keys is not None and k not in allowed_state_keys ): # Silently ignore invalid keys to match permissive session_state semantics return # Update the underlying stored base state and this dict super().__setitem__(k, v) try: # Store back to session state's widget store as a flat mapping ss = session_state # Directly set the value in the new widget state store if component_id is not None: ss._new_widget_state.set_from_value( component_id, dict(self) ) except Exception as e: _LOGGER.debug("Failed to persist CCv2 state update: %s", e) def __delitem__(self, k: str) -> None: _check_modification(k) super().__delitem__(k) try: ss = session_state if component_id is not None: ss._new_widget_state.set_from_value( component_id, dict(self) ) except Exception as e: _LOGGER.debug( "Failed to persist CCv2 state deletion: %s", e ) return _WriteThrough(flat) except Exception as e: # On any error, fall back to the base value _LOGGER.debug( "Failed to merge trigger events into component state: %s", e, exc_info=e, ) return base_value return base_value return _present
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/presentation.py", "license": "Apache License 2.0", "lines": 163, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/components/v2/bidi_component/test_serialization.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import json from typing import NoReturn import pandas as pd from streamlit.components.v2.bidi_component.serialization import ( BidiComponentSerde, _extract_dataframes_from_dict, deserialize_trigger_list, handle_deserialize, serialize_mixed_data, ) from streamlit.proto.BidiComponent_pb2 import BidiComponent as BidiComponentProto def test_handle_deserialize(): """Test handle_deserialize with valid JSON, invalid JSON, and None.""" assert handle_deserialize('{"key": "value"}') == {"key": "value"} assert handle_deserialize("not a json string") == "not a json string" assert handle_deserialize(None) is None def test_deserialize_trigger_list(): """Test deserialize_trigger_list with different payload formats.""" assert deserialize_trigger_list('[{"event": "click"}]') == [{"event": "click"}] assert deserialize_trigger_list('{"event": "click"}') == [{"event": "click"}] assert deserialize_trigger_list(None) is None def test_serde_deserialize_with_dict(): """Test deserialize with a dictionary.""" serde = BidiComponentSerde() state = serde.deserialize({"foo": "bar"}) assert state == {"foo": "bar"} def test_serde_deserialize_with_json_string(): """Test deserialize with a JSON string.""" serde = BidiComponentSerde() state = serde.deserialize('{"foo": "bar"}') assert state == {"foo": "bar"} def test_serde_deserialize_with_defaults(): """Test deserialize with default values.""" serde = BidiComponentSerde(default={"bar": "baz"}) state = serde.deserialize({"foo": "qux"}) assert state == {"foo": "qux", "bar": "baz"} def test_serde_deserialize_with_none(): """Test deserialize with None.""" serde = BidiComponentSerde() state = serde.deserialize(None) assert state == {} def test_serde_serialize(): """Test serialize.""" serde = BidiComponentSerde() serialized = serde.serialize({"foo": "bar"}) assert serialized == '{"foo": "bar"}' def test_serde_deserialize_with_defaults_empty_state(): """Test that defaults are applied when state is empty.""" defaults = {"count": 0, "message": "hello", "enabled": True} serde = BidiComponentSerde(default=defaults) # Deserialize empty state result = serde.deserialize(None) # Should have defaults applied assert result["count"] == 0 assert result["message"] == "hello" assert result["enabled"] is True def test_serde_deserialize_with_defaults_partial_state(): """Test that defaults are applied only for missing keys.""" defaults = {"count": 0, "message": "hello", "enabled": True} serde = BidiComponentSerde(default=defaults) # Deserialize partial state partial_state = {"count": 5, "message": "custom"} result = serde.deserialize(json.dumps(partial_state)) # Should preserve existing values and add missing defaults assert result["count"] == 5 # Existing value preserved assert result["message"] == "custom" # Existing value preserved assert result["enabled"] is True # Default applied def test_serde_deserialize_with_defaults_complete_state(): """Test that defaults don't override existing values.""" defaults = {"count": 0, "message": "hello"} serde = BidiComponentSerde(default=defaults) # Deserialize complete state complete_state = {"count": 10, "message": "world", "extra": "data"} result = serde.deserialize(json.dumps(complete_state)) # Should preserve all existing values assert result["count"] == 10 assert result["message"] == "world" assert result["extra"] == "data" def test_serde_deserialize_without_defaults(): """Test that serde works correctly without defaults.""" serde = BidiComponentSerde() # No defaults # Deserialize state state = {"count": 5} result = serde.deserialize(json.dumps(state)) # Should just return the state as-is assert result["count"] == 5 def test_serde_deserialize_with_invalid_json(): """Test that defaults are applied even with invalid JSON input.""" defaults = {"fallback": "value"} serde = BidiComponentSerde(default=defaults) # Deserialize invalid JSON result = serde.deserialize("invalid json {") # Should fall back to empty state with defaults applied assert result["fallback"] == "value" def test_serde_deserialize_with_dict_input_and_defaults(): """Test that defaults work with direct dict input.""" defaults = {"default_key": "default_value"} serde = BidiComponentSerde(default=defaults) # Deserialize dict input input_dict = {"existing_key": "existing_value"} result = serde.deserialize(input_dict) # Should merge defaults with existing assert result["existing_key"] == "existing_value" assert result["default_key"] == "default_value" def test_serde_deserialize_with_none_defaults(): """Test that None values in defaults are properly handled.""" defaults = {"nullable": None, "string": "value"} serde = BidiComponentSerde(default=defaults) # Deserialize empty state result = serde.deserialize(None) # Should apply None as a valid default assert result["nullable"] is None assert result["string"] == "value" def test_extract_dataframes_from_dict(): """Test _extract_dataframes_from_dict.""" df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) data = {"key1": "value1", "dataframe": df, "key2": 123} arrow_blobs = {} processed_data = _extract_dataframes_from_dict(data, arrow_blobs) assert "key1" in processed_data assert "key2" in processed_data assert "dataframe" in processed_data assert "__streamlit_arrow_ref__" in processed_data["dataframe"] assert len(arrow_blobs) == 1 def test_serialize_mixed_data_with_dataframe(): """Test serialize_mixed_data with a dataframe.""" df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) data = {"my_df": df, "other_key": "value"} proto = BidiComponentProto() serialize_mixed_data(data, proto) assert proto.HasField("mixed") assert not proto.HasField("json") mixed_data = json.loads(proto.mixed.json) assert "my_df" in mixed_data assert "__streamlit_arrow_ref__" in mixed_data["my_df"] assert len(proto.mixed.arrow_blobs) == 1 def test_serialize_mixed_data_without_dataframe(): """Test serialize_mixed_data without a dataframe.""" data = {"key": "value"} proto = BidiComponentProto() serialize_mixed_data(data, proto) assert not proto.HasField("mixed") assert proto.HasField("json") assert json.loads(proto.json) == data def test_serialize_mixed_data_with_non_dict(): """Test serialize_mixed_data with non-dictionary data.""" data = [1, 2, 3] proto = BidiComponentProto() serialize_mixed_data(data, proto) assert not proto.HasField("mixed") assert proto.HasField("json") assert json.loads(proto.json) == data def test_serialization_fallback_to_string(): """Test that serialization falls back to string representation on failure.""" # Sets are not directly JSON-serializable data = {"key": {1, 2, 3}} proto = BidiComponentProto() serialize_mixed_data(data, proto) assert not proto.HasField("mixed") assert proto.HasField("json") assert json.loads(proto.json) == str(data) def test_extract_dataframes_from_dict_fallback_on_arrow_failure(monkeypatch): """If Arrow serialization fails for a dataframe-like value, the original value should be preserved.""" from streamlit.components.v2.bidi_component import serialization as ser class Sentinel: pass obj = Sentinel() # Force detection as dataframe-like but make conversion raise. monkeypatch.setattr(ser, "is_dataframe_like", lambda v: v is obj) def _boom(_: object) -> NoReturn: raise Exception("boom") monkeypatch.setattr(ser, "convert_anything_to_arrow_bytes", _boom) result = ser._extract_dataframes_from_dict({"df": obj}) assert result["df"] is obj
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/bidi_component/test_serialization.py", "license": "Apache License 2.0", "lines": 188, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/components/v2/bidi_component/test_state.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from streamlit.components.v2.bidi_component.state import BidiComponentResult def test_bidi_component_result_empty() -> None: """Test empty result handling.""" result = BidiComponentResult() assert dict(result) == {} def test_bidi_component_result_merges_state_and_trigger_values() -> None: """Test that BidiComponentResult surfaces trigger and state values.""" state_vals = {"foo": "bar"} trigger_vals = {"on_click": 42} result = BidiComponentResult(state_vals=state_vals, trigger_vals=trigger_vals) assert result["foo"] == "bar" assert result.foo == "bar" assert result["on_click"] == 42 assert result.on_click == 42 assert "delta_generator" not in result def test_bidi_component_result_merge_order() -> None: """Test that trigger keys precede state keys and state overrides duplicates.""" state_vals = {"shared": "state", "state_only": "value"} trigger_vals = {"shared": "trigger", "trigger_only": "value"} result = BidiComponentResult(state_vals=state_vals, trigger_vals=trigger_vals) assert list(result.keys()) == ["shared", "trigger_only", "state_only"] assert result.shared == "state"
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/bidi_component/test_state.py", "license": "Apache License 2.0", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/components/v2/test_bidi_component.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import json import math from typing import Any from unittest.mock import MagicMock, patch import pandas as pd import pytest import streamlit as st from streamlit import _main as st_main from streamlit.components.v2.bidi_component.constants import EVENT_DELIM from streamlit.components.v2.bidi_component.main import ( BidiComponentMixin, _make_trigger_id, ) from streamlit.components.v2.bidi_component.state import BidiComponentResult from streamlit.components.v2.component_manager import BidiComponentManager from streamlit.components.v2.component_registry import BidiComponentDefinition from streamlit.errors import ( BidiComponentInvalidCallbackNameError, StreamlitAPIException, ) from streamlit.proto.BidiComponent_pb2 import BidiComponent as BidiComponentProto from streamlit.proto.WidgetStates_pb2 import WidgetState, WidgetStates from streamlit.runtime import Runtime from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx from streamlit.runtime.state.session_state import ( STREAMLIT_INTERNAL_KEY_PREFIX, _is_internal_key, ) from streamlit.util import calc_md5 from tests.delta_generator_test_case import DeltaGeneratorTestCase def test_event_delim_is_double_underscore(): """Test that the EVENT_DELIM constant has the correct value.""" assert EVENT_DELIM == "__", ( f"EVENT_DELIM must be set to the string '__'. Found {EVENT_DELIM!r} instead." ) @pytest.mark.parametrize( ("base", "event", "expected"), [ ("comp", "click", "comp__click"), ("component123", "change", "component123__change"), ("Ξ”elta", "πŸš€", "Ξ”elta__πŸš€"), # Unicode should be preserved ], ) def test_make_trigger_id_constructs_valid_id(base: str, event: str, expected: str): """Test that _make_trigger_id constructs a valid trigger ID for various inputs.""" assert _make_trigger_id(base, event) == f"$$STREAMLIT_INTERNAL_KEY_{expected}" def test_make_trigger_id_validates_base_delimiter() -> None: """Test that _make_trigger_id raises exception if base contains delimiter.""" with pytest.raises(StreamlitAPIException, match="delimiter sequence"): _make_trigger_id("base__with__delim", "click") def test_make_trigger_id_validates_event_delimiter() -> None: """Test that _make_trigger_id raises exception if event contains delimiter.""" with pytest.raises(StreamlitAPIException, match="delimiter sequence"): _make_trigger_id("normal_base", "click__event") def test_make_trigger_id_creates_internal_key() -> None: """Test that _make_trigger_id creates widget IDs with internal prefix. Trigger widgets should be marked as internal so they don't appear in st.session_state when accessed by end users. """ base_id = "my_component_123" event = "click" trigger_id = _make_trigger_id(base_id, event) # Should start with internal prefix assert trigger_id.startswith(STREAMLIT_INTERNAL_KEY_PREFIX), ( f"Trigger ID should start with {STREAMLIT_INTERNAL_KEY_PREFIX}, got: {trigger_id}" ) # Should contain the base component ID assert base_id in trigger_id, ( f"Trigger ID should contain base '{base_id}', got: {trigger_id}" ) # Should contain the event name assert event in trigger_id, ( f"Trigger ID should contain event '{event}', got: {trigger_id}" ) # Should contain the event delimiter assert EVENT_DELIM in trigger_id, ( f"Trigger ID should contain delimiter '{EVENT_DELIM}', got: {trigger_id}" ) def test_trigger_id_is_detected_as_internal() -> None: """Test that trigger widget IDs are correctly identified as internal keys.""" base_id = "my_component_123" event = "click" trigger_id = _make_trigger_id(base_id, event) # Trigger ID should be detected as internal assert _is_internal_key(trigger_id), ( f"Trigger ID should be detected as internal: {trigger_id}" ) def test_regular_keys_are_not_detected_as_internal() -> None: """Test that regular keys and widget IDs are not detected as internal.""" regular_key = "user_defined_key" regular_widget_id = "$$ID-my_widget-None" # Typical auto-generated widget ID component_id = "my_component_main_widget" # Component main widget ID # Regular keys should not be detected as internal assert not _is_internal_key(regular_key), ( f"Regular key should not be detected as internal: {regular_key}" ) assert not _is_internal_key(regular_widget_id), ( f"Regular widget ID should not be detected as internal: {regular_widget_id}" ) assert not _is_internal_key(component_id), ( f"Component ID should not be detected as internal: {component_id}" ) def test_make_trigger_id_normal_case() -> None: """Test that _make_trigger_id works correctly for normal inputs.""" base_id = "normal_base" event = "normal_event" trigger_id = _make_trigger_id(base_id, event) # Should succeed and return a valid internal key assert trigger_id is not None assert _is_internal_key(trigger_id) assert base_id in trigger_id assert event in trigger_id def test_multiple_trigger_ids_are_all_internal() -> None: """Test that multiple trigger IDs for the same component are all internal.""" base_id = "my_component_456" events = ["click", "change", "submit", "hover"] trigger_ids = [_make_trigger_id(base_id, event) for event in events] # All trigger IDs should be internal for trigger_id in trigger_ids: assert _is_internal_key(trigger_id), ( f"All trigger IDs should be internal: {trigger_id}" ) # All trigger IDs should be unique assert len(trigger_ids) == len(set(trigger_ids)), "All trigger IDs should be unique" def test_result_merges_state_and_trigger_values_and_exposes_dg(): """BidiComponentResult should behave like a mapping/attribute dict and expose the dg.""" # Arrange state_vals = {"foo": 123, "bar": "abc"} trigger_vals = {"clicked": True, "changed": {"value": 42}} # Act result = BidiComponentResult(state_vals, trigger_vals) # Assert mapping access assert result["foo"] == 123 assert result["bar"] == "abc" assert result["clicked"] is True assert result["changed"] == {"value": 42} # Assert attribute access assert result.foo == 123 assert result.bar == "abc" assert result.clicked is True assert result.changed == {"value": 42} def test_make_trigger_id_is_idempotent(): """Test that _make_trigger_id is idempotent.""" base, event = "foo", "bar" first = _make_trigger_id(base, event) second = _make_trigger_id(base, event) assert first == second == "$$STREAMLIT_INTERNAL_KEY_foo__bar" def test_make_trigger_id_rejects_delimiter_in_base_or_event(): """Test that _make_trigger_id rejects delimiters in base or event names.""" with pytest.raises(StreamlitAPIException): _make_trigger_id("bad__base", "click") with pytest.raises(StreamlitAPIException): _make_trigger_id("base", "bad__event") class BidiComponentInvalidCallbackNameErrorTest(DeltaGeneratorTestCase): """Test that BidiComponentInvalidCallbackNameError is raised when invalid callback names are provided.""" def setUp(self): super().setUp() manager = Runtime.instance().bidi_component_registry component_def = BidiComponentDefinition( name="my_component", js="console.log('hello');", ) manager.register(component_def) self.dg = st_main def test_bidi_component_disallowed_on_change_callbacks(self): """Test that `on_change` and `on__change` are disallowed as callbacks.""" with pytest.raises(BidiComponentInvalidCallbackNameError): self.dg._bidi_component( "my_component", key="key1", on_change=lambda: None, ) with pytest.raises(BidiComponentInvalidCallbackNameError): self.dg._bidi_component( "my_component", key="key2", on__change=lambda: None, ) class BidiComponentMixinTest(DeltaGeneratorTestCase): """Validate bi-directional component mixin behavior. This suite verifies: - Parsing of ``on_<event>_change`` kwargs into an event-to-callback mapping - Registration of the per-run aggregator trigger widget with ``value_type`` equal to ``"json_trigger_value"`` - ``BidiComponentResult`` exposes event keys and merges persistent state with trigger values - Callbacks and widget metadata are correctly stored in ``SessionState`` for the current run """ def setUp(self): super().setUp() # Create and inject a fresh component manager for each test run self.component_manager = BidiComponentManager() runtime = Runtime.instance() if runtime is None: raise RuntimeError("Runtime.instance() returned None in test setup.") runtime.bidi_component_registry = self.component_manager # --------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------- def _register_dummy_component(self, name: str = "dummy") -> None: self.component_manager.register( BidiComponentDefinition(name=name, js="console.log('hi');") ) # --------------------------------------------------------------------- # Tests # --------------------------------------------------------------------- def test_event_callback_parsing_and_trigger_widget_registration(self): """Providing ``on_click_change`` should register a trigger widget.""" self._register_dummy_component() on_click_cb = MagicMock(name="on_click_cb") on_hover_cb = MagicMock(name="on_hover_cb") # Act result = st._bidi_component( "dummy", on_click_change=on_click_cb, on_hover_change=on_hover_cb, ) # ------------------------------------------------------------------ # Assert - return type & merged keys # ------------------------------------------------------------------ assert isinstance(result, BidiComponentResult) # No state set yet, but we expect trigger keys to exist with None assert "click" in result assert result.click is None assert "hover" in result assert result.hover is None # ------------------------------------------------------------------ # Assert - trigger widget metadata # ------------------------------------------------------------------ ctx = get_script_run_ctx() assert ctx is not None, "ScriptRunContext missing in test" # Compute expected aggregator trigger id base_id = next( wid for wid in ctx.widget_ids_this_run if wid.startswith("$$ID") and EVENT_DELIM not in wid ) aggregator_id = _make_trigger_id(base_id, "events") # Access internal SessionState to retrieve widget metadata. internal_state = ctx.session_state._state # SessionState instance metadata_aggregator = internal_state._new_widget_state.widget_metadata[ aggregator_id ] assert metadata_aggregator.value_type == "json_trigger_value" # The callbacks must be wired by event name in metadata assert metadata_aggregator.callbacks == { "click": on_click_cb, "hover": on_hover_cb, } class BidiComponentTest(DeltaGeneratorTestCase): """Test the bidi_component functionality.""" def setUp(self): super().setUp() # Create a mock component manager for testing self.mock_component_manager = BidiComponentManager() # Patch the Runtime to return our mock component manager self.runtime_patcher = patch.object( Runtime, "instance", return_value=MagicMock() ) self.mock_runtime = self.runtime_patcher.start() self.mock_runtime.return_value.bidi_component_registry = ( self.mock_component_manager ) def tearDown(self): super().tearDown() self.runtime_patcher.stop() def test_component_with_js_content_only(self): """Test component with only JavaScript content.""" # Register a component with JS content only self.mock_component_manager.register( BidiComponentDefinition( name="js_only_component", js="console.log('hello world');", ) ) # Call the component st._bidi_component("js_only_component") # Verify the proto was enqueued delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "js_only_component" assert bidi_component_proto.js_content == "console.log('hello world');" assert bidi_component_proto.html_content == "" def test_component_with_html_content_only(self): """Test component with only HTML content.""" # Register a component with HTML content only self.mock_component_manager.register( BidiComponentDefinition( name="html_only_component", html="<div>Hello World</div>", ) ) # Call the component st._bidi_component("html_only_component") # Verify the proto was enqueued delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "html_only_component" assert bidi_component_proto.html_content == "<div>Hello World</div>" assert bidi_component_proto.js_content == "" def test_component_with_js_url_only(self): """Test component with only JavaScript URL.""" # Create a mock component definition with js_url mock_component_def = MagicMock(spec=BidiComponentDefinition) mock_component_def.js_content = None mock_component_def.js_url = "index.js" mock_component_def.html_content = None mock_component_def.css_content = None mock_component_def.css_url = None mock_component_def.isolate_styles = True # Mock the registry to return our component with patch.object( self.mock_component_manager, "get", return_value=mock_component_def ): # Call the component st._bidi_component("js_url_component") # Verify the proto was enqueued delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "js_url_component" assert bidi_component_proto.js_source_path == "index.js" assert bidi_component_proto.html_content == "" def test_component_with_both_js_and_html(self): """Test component with both JavaScript and HTML content.""" # Register a component with both JS and HTML content self.mock_component_manager.register( BidiComponentDefinition( name="full_component", js="console.log('hello world');", html="<div>Hello World</div>", css="div { color: red; }", ) ) # Call the component st._bidi_component("full_component") # Verify the proto was enqueued delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "full_component" assert bidi_component_proto.js_content == "console.log('hello world');" assert bidi_component_proto.html_content == "<div>Hello World</div>" assert bidi_component_proto.css_content == "div { color: red; }" def test_component_with_css_only_succeeds(self): """Test that a CSS-only component mounts without raising.""" self.mock_component_manager.register( BidiComponentDefinition( name="css_only_component", css="div { color: red; }", ) ) st._bidi_component("css_only_component") delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "css_only_component" assert bidi_component_proto.css_content == "div { color: red; }" assert bidi_component_proto.js_content == "" assert bidi_component_proto.html_content == "" def test_component_with_no_content_succeeds(self): """Test that a component with no JS/HTML/CSS mounts without raising.""" self.mock_component_manager.register( BidiComponentDefinition( name="empty_component", ) ) st._bidi_component("empty_component") delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "empty_component" assert bidi_component_proto.css_content == "" assert bidi_component_proto.js_content == "" assert bidi_component_proto.html_content == "" def test_unregistered_component_raises_value_error(self): """Test that calling an unregistered component raises ValueError.""" # Call a component that doesn't exist with pytest.raises( ValueError, match="Component 'nonexistent_component' is not registered" ): st._bidi_component("nonexistent_component") def test_component_with_key(self): """Test component with a user-specified key.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="keyed_component", js="console.log('hello world');", ) ) # Call the component with a key st._bidi_component("keyed_component", key="my_key") # Verify the proto was enqueued with the correct ID delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "keyed_component" # The ID should be deterministic based on the key assert bidi_component_proto.id is not None def test_component_with_scalar_data(self): """Test component with scalar data parameter serialized as JSON.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="data_component", js="console.log('hello world');", ) ) # Use a simple scalar value which is treated as DataFormat.UNKNOWN and therefore JSON-encoded test_data = "hello streamlit" st._bidi_component("data_component", data=test_data) # Verify the proto was enqueued with the data delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "data_component" # Data should be JSON serialized inside the `json` oneof field assert bidi_component_proto.WhichOneof("data") == "json" assert bidi_component_proto.json == '"hello streamlit"' def test_component_with_dict_data_json(self): """Test component with dict data serialized as JSON.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="dict_data_component", js="console.log('hello world');", ) ) test_dict = {"message": "hello", "count": 42} st._bidi_component("dict_data_component", data=test_dict) delta = self.get_delta_from_queue() proto = delta.new_element.bidi_component assert proto.component_name == "dict_data_component" # Should choose JSON path assert proto.WhichOneof("data") == "json" assert json.loads(proto.json) == test_dict def test_component_with_arrow_data(self): """Test component with dataframe-like data serialized to Arrow.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="arrow_data_component", js="console.log('hello world');", ) ) # Use a simple Pandas DataFrame which should be detected as dataframe-like df = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]}) st._bidi_component("arrow_data_component", data=df) # Verify the proto was enqueued with Arrow data delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "arrow_data_component" assert bidi_component_proto.WhichOneof("data") == "arrow_data" # The Arrow bytes should be non-empty assert len(bidi_component_proto.arrow_data.data) > 0 def test_component_with_bytes_data(self): """Test component with raw bytes data passed through unchanged.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="bytes_data_component", js="console.log('hello world');", ) ) # Raw bytes payload binary_payload = b"\x00\x01\x02streamlit" st._bidi_component("bytes_data_component", data=binary_payload) # Verify the proto was enqueued with bytes data delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "bytes_data_component" assert bidi_component_proto.WhichOneof("data") == "bytes" assert bidi_component_proto.bytes == binary_payload def test_component_with_callbacks(self): """Test component with callback handlers.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="callback_component", js="console.log('hello world');", ) ) # Create mock callback on_click_callback = MagicMock() # Call the component with event-specific callback result = st._bidi_component( "callback_component", on_click_change=on_click_callback, ) # Verify the result assert hasattr(result, "click") # Verify the proto was enqueued with registered handler names delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "callback_component" def test_component_with_dict_containing_dataframe(self): """Test component with dict containing dataframe - should use mixed data serialization.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="dict_with_df_component", js="console.log('hello world');", ) ) # Create mixed data with dataframe automatically detected df = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]}) mixed_data = { "config": {"title": "My Chart", "theme": "dark"}, "dataframe": df, # This should be automatically detected and converted "metadata": {"rows": 3, "cols": 2}, } st._bidi_component("dict_with_df_component", data=mixed_data) # Verify the proto was enqueued with mixed data delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "dict_with_df_component" assert bidi_component_proto.WhichOneof("data") == "mixed" # Verify the mixed data structure mixed_proto = bidi_component_proto.mixed assert mixed_proto.json is not None assert len(mixed_proto.arrow_blobs) == 1 # Parse the JSON to verify placeholder structure parsed_json = json.loads(mixed_proto.json) assert parsed_json["config"]["title"] == "My Chart" assert parsed_json["metadata"]["rows"] == 3 # The dataframe should be replaced with a placeholder assert "__streamlit_arrow_ref__" in parsed_json["dataframe"] def test_component_with_multiple_dataframes_in_dict(self): """Test component with dict containing multiple dataframes.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="multi_df_component", js="console.log('hello world');", ) ) # Create mixed data with multiple dataframes df1 = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]}) df2 = pd.DataFrame({"c": [4, 5, 6], "d": ["p", "q", "r"]}) mixed_data = { "config": {"title": "My Chart", "theme": "dark"}, "sales_data": df1, # Should be automatically detected "inventory_data": df2, # Should be automatically detected "metadata": {"rows": 3, "cols": 2}, } st._bidi_component("multi_df_component", data=mixed_data) # Verify the proto was enqueued with mixed data delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "multi_df_component" assert bidi_component_proto.WhichOneof("data") == "mixed" # Verify the mixed data structure mixed_proto = bidi_component_proto.mixed assert mixed_proto.json is not None assert len(mixed_proto.arrow_blobs) == 2 # Two dataframes # Parse the JSON to verify placeholder structure parsed_json = json.loads(mixed_proto.json) assert parsed_json["config"]["title"] == "My Chart" assert parsed_json["config"]["theme"] == "dark" assert parsed_json["metadata"]["rows"] == 3 # Both dataframes should be replaced with placeholders assert "__streamlit_arrow_ref__" in parsed_json["sales_data"] assert "__streamlit_arrow_ref__" in parsed_json["inventory_data"] def test_component_with_dict_without_dataframes(self): """Test component with dict containing no dataframes - should use JSON serialization.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="json_only_component", js="console.log('hello world');", ) ) # Create data with no dataframes data = { "config": {"theme": "dark", "height": 400}, "labels": ["A", "B", "C"], "settings": {"enabled": True}, "metadata": {"version": "1.0"}, } st._bidi_component("json_only_component", data=data) # Verify the proto was enqueued with JSON serialization delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "json_only_component" assert bidi_component_proto.WhichOneof("data") == "json" # Parse the JSON to verify it matches original data parsed_json = json.loads(bidi_component_proto.json) assert parsed_json == data def test_component_with_list_data(self): """Test component with list data - should use JSON serialization.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="list_component", js="console.log('hello world');", ) ) # Create list data (no automatic dataframe detection for lists) df = pd.DataFrame({"col": [1, 2, 3]}) list_data = [ {"name": "dataset1", "values": [1, 2, 3]}, {"name": "dataset2", "values": [4, 5, 6]}, df, # This dataframe will be converted to JSON via fallback ] st._bidi_component("list_component", data=list_data) # Verify the proto was enqueued with JSON serialization # (since we only detect dataframes in first level of dicts) delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "list_component" assert bidi_component_proto.WhichOneof("data") == "json" # The data should be JSON-serialized as a string (due to DataFrame fallback) parsed_json = json.loads(bidi_component_proto.json) assert isinstance(parsed_json, str) # It's a string representation assert "dataset1" in parsed_json assert "dataset2" in parsed_json def test_component_with_tuple_data(self): """Test component with tuple data - should use JSON serialization.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="tuple_component", js="console.log('hello world');", ) ) # Create tuple data (no automatic dataframe detection for tuples) df = pd.DataFrame({"value": [42]}) tuple_data = ("metadata", df, {"extra": "info"}) st._bidi_component("tuple_component", data=tuple_data) # Verify the proto was enqueued with JSON serialization # (since we only detect dataframes in first level of dicts) delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.component_name == "tuple_component" assert bidi_component_proto.WhichOneof("data") == "json" # The data should be JSON-serialized as a string (due to DataFrame fallback) parsed_json = json.loads(bidi_component_proto.json) # The tuple with DataFrame gets converted to string representation assert isinstance(parsed_json, str) assert "metadata" in parsed_json assert "extra" in parsed_json assert "info" in parsed_json def test_component_with_dict_no_arrow_refs_uses_json(self): """Test that dictionaries without ArrowReference objects use regular JSON serialization.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="json_only_component", js="console.log('hello world');", ) ) # Create dictionary without any ArrowReference objects regular_data = { "config": {"title": "Chart", "enabled": True}, "values": [1, 2, 3, 4], "metadata": {"count": 4}, } st._bidi_component("json_only_component", data=regular_data) # Verify the proto uses regular JSON serialization delta = self.get_delta_from_queue() bidi_component_proto = delta.new_element.bidi_component assert bidi_component_proto.WhichOneof("data") == "json" parsed_data = json.loads(bidi_component_proto.json) assert parsed_data == regular_data def test_default_with_valid_callbacks(self): """Test that default works correctly with valid callback names.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="default_component", js="console.log('hello world');", ) ) # Create mock callbacks on_selected_change = MagicMock() on_search_change = MagicMock() # Call the component with default result = st._bidi_component( "default_component", default={ "selected": ["item1", "item2"], "search": "default search", }, on_selected_change=on_selected_change, on_search_change=on_search_change, ) # Verify the result contains default values assert result["selected"] == ["item1", "item2"] assert result["search"] == "default search" def test_default_validation_error(self): """Test that invalid keys in default raise StreamlitAPIException.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="validation_component", js="console.log('hello world');", ) ) # Create mock callback for only one state on_valid_change = MagicMock() # Call the component with invalid default key with pytest.raises(StreamlitAPIException) as exc_info: st._bidi_component( "validation_component", default={ "valid": "this is ok", "invalid": "this should fail", # No on_invalid_change callback }, on_valid_change=on_valid_change, ) # Verify the error message error_message = str(exc_info.value) assert "invalid" in error_message assert "not a valid state name" in error_message assert "Available state names: `['valid']`" in error_message def test_default_no_callbacks_error(self): """Test that default with no callbacks raises StreamlitAPIException.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="no_callbacks_component", js="console.log('hello world');", ) ) # Call the component with default but no callbacks with pytest.raises(StreamlitAPIException) as exc_info: st._bidi_component( "no_callbacks_component", default={"some_state": "value"}, ) # Verify the error message mentions no available state names error_message = str(exc_info.value) assert "some_state" in error_message assert "not a valid state name" in error_message assert "Available state names: `none`" in error_message def test_default_none_is_valid(self): """Test that default=None works correctly.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="none_default_component", js="console.log('hello world');", ) ) # Create mock callback on_test_change = MagicMock() # Call the component with default=None result = st._bidi_component( "none_default_component", default=None, on_test_change=on_test_change, ) # Should work without error and have empty state assert result["test"] is None def test_default_empty_dict(self): """Test that empty default dict works correctly.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="empty_default_component", js="console.log('hello world');", ) ) # Create mock callback on_test_change = MagicMock() # Call the component with empty default result = st._bidi_component( "empty_default_component", default={}, on_test_change=on_test_change, ) # Should work without error assert result["test"] is None def test_default_with_none_values(self): """Test that None values in default are properly handled.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="none_values_component", js="console.log('hello world');", ) ) # Create mock callback on_nullable_change = MagicMock() # Call the component with None default value result = st._bidi_component( "none_values_component", default={"nullable": None}, on_nullable_change=on_nullable_change, ) # Verify None is properly set as default assert result["nullable"] is None def test_default_complex_values(self): """Test that complex values in default work correctly.""" # Register a component self.mock_component_manager.register( BidiComponentDefinition( name="complex_default_component", js="console.log('hello world');", ) ) # Create mock callbacks on_list_state_change = MagicMock() on_dict_state_change = MagicMock() # Call the component with complex default values complex_list = [1, 2, {"nested": "value"}] complex_dict = {"key": "value", "nested": {"data": [1, 2, 3]}} result = st._bidi_component( "complex_default_component", default={ "list_state": complex_list, "dict_state": complex_dict, }, on_list_state_change=on_list_state_change, on_dict_state_change=on_dict_state_change, ) # Verify complex values are properly set assert result["list_state"] == complex_list assert result["dict_state"] == complex_dict class BidiComponentIdentityTest(DeltaGeneratorTestCase): """Validate CCv2 identity rules for keyed and unkeyed instances.""" def setUp(self): super().setUp() self.manager = BidiComponentManager() runtime = Runtime.instance() if runtime is None: raise RuntimeError("Runtime.instance() returned None in test setup.") runtime.bidi_component_registry = self.manager self.manager.register( BidiComponentDefinition(name="ident", js="console.log('hi');") ) def _clear_widget_registrations_for_current_run(self) -> None: """Allow re-registering the same id within the same run for testing keyed stability.""" ctx = get_script_run_ctx() assert ctx is not None ctx.widget_user_keys_this_run.clear() ctx.widget_ids_this_run.clear() def _render_and_get_id(self) -> str: delta = self.get_delta_from_queue() return delta.new_element.bidi_component.id def test_unkeyed_id_stable_when_data_is_none(self): """Without data, unkeyed components should have stable IDs based on other params.""" st._bidi_component("ident") id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component("ident") id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_differs_between_none_and_empty_data(self): """data=None must produce a different ID than data={} (empty dict is still data).""" st._bidi_component("ident", data=None) id_none = self._render_and_get_id() st._bidi_component("ident", data={}) id_empty = self._render_and_get_id() assert id_none != id_empty def test_unkeyed_id_changes_when_json_data_changes(self): """Without a user key, changing JSON data must change the backend id.""" st._bidi_component("ident", data={"x": 1}) id1 = self._render_and_get_id() st._bidi_component("ident", data={"x": 2}) id2 = self._render_and_get_id() assert id1 != id2 def test_unkeyed_id_changes_when_bytes_change(self): """Without a user key, changing bytes must change the backend id.""" st._bidi_component("ident", data=b"abc") id1 = self._render_and_get_id() st._bidi_component("ident", data=b"abcd") id2 = self._render_and_get_id() assert id1 != id2 def test_unkeyed_id_changes_when_arrow_data_changes(self): """Without a user key, changing dataframe content must change the backend id.""" st._bidi_component("ident", data=pd.DataFrame({"a": [1, 2]})) id1 = self._render_and_get_id() st._bidi_component("ident", data=pd.DataFrame({"a": [1, 3]})) id2 = self._render_and_get_id() assert id1 != id2 def test_unkeyed_id_changes_when_mixed_blobs_change(self): """Without a user key, MixedData blob fingerprint differences must change id.""" st._bidi_component("ident", data={"df": pd.DataFrame({"x": [1]})}) id1 = self._render_and_get_id() st._bidi_component("ident", data={"df": pd.DataFrame({"x": [2]})}) id2 = self._render_and_get_id() assert id1 != id2 def test_keyed_id_stable_when_data_changes_json(self): """With a user key, changing JSON data must NOT change the backend id (same run).""" st._bidi_component("ident", key="K", data={"v": 1}) id1 = self._render_and_get_id() # Allow re-registering the same id in the same run for test purposes self._clear_widget_registrations_for_current_run() st._bidi_component("ident", key="K", data={"v": 2}) id2 = self._render_and_get_id() assert id1 == id2 def test_keyed_id_stable_when_mixed_data_changes(self): """With a user key, changing MixedData (JSON + blobs) must NOT change the backend id (same run).""" st._bidi_component( "ident", key="MIX", data={"df": pd.DataFrame({"a": [1]}), "m": {"x": 1}} ) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component( "ident", key="MIX", data={"df": pd.DataFrame({"a": [2]}), "m": {"x": 2}} ) id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_stable_when_arrow_data_unchanged(self): """Without a user key, unchanged dataframe content must keep the same backend id (no needless churn).""" df1 = pd.DataFrame({"a": [1, 2, 3]}) st._bidi_component("ident", data=df1) id1 = self._render_and_get_id() # Allow re-registering the same id in this run for stability assertion self._clear_widget_registrations_for_current_run() # New DataFrame object with identical content df2 = pd.DataFrame({"a": [1, 2, 3]}) st._bidi_component("ident", data=df2) id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_stable_when_mixed_data_unchanged(self): """Without a user key, unchanged MixedData must keep the same backend id (no needless churn).""" mixed1 = {"df": pd.DataFrame({"x": [1, 2]}), "meta": {"k": "v"}} st._bidi_component("ident", data=mixed1) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() # New objects but same serialized content and key order mixed2 = {"df": pd.DataFrame({"x": [1, 2]}), "meta": {"k": "v"}} st._bidi_component("ident", data=mixed2) id2 = self._render_and_get_id() assert id1 == id2 def test_keyed_id_stable_when_data_changes_arrow(self): """With a user key, changing Arrow/mixed data must NOT change the backend id (same run).""" st._bidi_component("ident", key="ARW", data=pd.DataFrame({"a": [1]})) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component("ident", key="ARW", data=pd.DataFrame({"a": [2]})) id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_stable_when_default_unchanged(self): """Without a user key, unchanged defaults must keep the same backend id.""" st._bidi_component( "ident", default={"foo": 1}, on_foo_change=MagicMock(), ) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component( "ident", default={"foo": 1}, on_foo_change=MagicMock(), ) id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_changes_when_default_changes(self): """Without a user key, changing defaults must change the backend id.""" st._bidi_component( "ident", default={"foo": 1}, on_foo_change=MagicMock(), ) id1 = self._render_and_get_id() st._bidi_component( "ident", default={"foo": 2}, on_foo_change=MagicMock(), ) id2 = self._render_and_get_id() assert id1 != id2 def test_keyed_id_stable_when_default_changes(self): """With a user key, changing defaults must NOT change the backend id (same run).""" st._bidi_component( "ident", key="DEF", default={"foo": 1}, on_foo_change=MagicMock(), ) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component( "ident", key="DEF", default={"foo": 2}, on_foo_change=MagicMock(), ) id2 = self._render_and_get_id() assert id1 == id2 def test_identity_kwargs_raises_on_unhandled_oneof(self): """_build_bidi_identity_kwargs should raise if an unknown oneof is encountered.""" mixin = BidiComponentMixin() class DummyProto: def WhichOneof(self, _name: str) -> str: return "new_unhandled_field" with pytest.raises( RuntimeError, match=r"Unhandled BidiComponent\.data oneof field" ): mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=DummyProto(), # type: ignore[arg-type] ) def test_identity_kwargs_mixed_blob_keys_are_sorted(self): """When computing identity, mixed arrow blob ref IDs must be sorted for stability.""" mixin = BidiComponentMixin() proto = BidiComponentProto() proto.mixed.json = "{}" # Insert keys in descending order to verify sorting in identity. proto.mixed.arrow_blobs["b"].data = b"b" proto.mixed.arrow_blobs["a"].data = b"a" identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, ) assert identity["mixed_json"] == calc_md5("{}") assert identity["mixed_arrow_blobs"] == "a,b" def test_identity_kwargs_json_canonicalizes_order(self): """Identity canonicalization should ignore key insertion order for JSON data.""" mixin = BidiComponentMixin() proto = BidiComponentProto() proto.json = json.dumps({"b": 2, "a": 1}) identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, ) expected = json.dumps({"a": 1, "b": 2}, sort_keys=True) assert identity["json"] == calc_md5(expected) def test_identity_kwargs_mixed_json_canonicalizes_order(self): """MixedData identity must canonicalize JSON portion independently of storage order.""" mixin = BidiComponentMixin() proto = BidiComponentProto() proto.mixed.json = json.dumps({"b": 2, "a": 1}) identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, ) expected = json.dumps({"a": 1, "b": 2}, sort_keys=True) assert identity["mixed_json"] == calc_md5(expected) def test_identity_kwargs_bytes_use_digest(self): """Raw byte payloads should contribute content digests, not the full payload.""" mixin = BidiComponentMixin() proto = BidiComponentProto() proto.bytes = b"bytes payload" identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, ) assert identity["bytes"] == calc_md5(b"bytes payload") def test_identity_kwargs_arrow_data_use_digest(self): """Arrow payloads should contribute digests to avoid hashing large blobs repeatedly.""" mixin = BidiComponentMixin() proto = BidiComponentProto() proto.arrow_data.data = b"\x00\x01" identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, ) assert identity["arrow_data"] == calc_md5(b"\x00\x01") def test_unkeyed_id_stable_when_json_key_order_changes(self): """Without a user key, changing the insertion order of keys in a JSON dict should NOT change the backend id.""" data1 = {"a": 1, "b": 2} data2 = {"b": 2, "a": 1} st._bidi_component("ident", data=data1) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component("ident", data=data2) id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_stable_when_mixed_data_json_key_order_changes(self): """Without a user key, changing the insertion order of keys in the JSON part of MixedData should NOT change the backend id.""" # We use different dataframes (same content) to trigger mixed processing but keep blobs same df1 = pd.DataFrame({"c": [3]}) df2 = pd.DataFrame({"c": [3]}) data1 = {"df": df1, "meta": {"a": 1, "b": 2}} data2 = {"df": df2, "meta": {"b": 2, "a": 1}} st._bidi_component("ident", data=data1) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() st._bidi_component("ident", data=data2) id2 = self._render_and_get_id() assert id1 == id2 def test_unkeyed_id_stable_with_duplicate_dataframe_content(self): """Two different keys with identical DataFrame content should produce stable IDs. This validates content-addressing deduplication: identical DataFrames under different keys share the same blob ref ID, so the identity is stable. """ data1 = {"df1": pd.DataFrame({"x": [1]}), "df2": pd.DataFrame({"x": [1]})} st._bidi_component("ident", data=data1) id1 = self._render_and_get_id() self._clear_widget_registrations_for_current_run() # Same structure, new DataFrame objects with identical content data2 = {"df1": pd.DataFrame({"x": [1]}), "df2": pd.DataFrame({"x": [1]})} st._bidi_component("ident", data=data2) id2 = self._render_and_get_id() assert id1 == id2 def test_identity_kwargs_uses_optimization_when_data_provided(self): """When data is provided, identity calculation should skip unnecessary deserialization.""" mixin = BidiComponentMixin() proto = BidiComponentProto() data = {"a": 1, "b": 2} # Pre-populate proto.json to simulate what happens in main proto.json = json.dumps(data) # Mock _canonical_json_digest_for_identity to ensure it's NOT called # when the optimization path is taken. with patch.object(mixin, "_canonical_json_digest_for_identity") as mock_digest: identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, data=data, ) # Verify the result is correct (sorted keys) expected_canonical = json.dumps(data, sort_keys=True) assert identity["json"] == calc_md5(expected_canonical) # Verify the slow path was skipped mock_digest.assert_not_called() # Verify behavior WITHOUT data (slow path fallback) with patch.object( mixin, "_canonical_json_digest_for_identity", wraps=mixin._canonical_json_digest_for_identity, ) as mock_digest: identity = mixin._build_bidi_identity_kwargs( component_name="cmp", isolate_styles=True, width="stretch", height="content", proto=proto, data=None, ) # Verify result is still correct assert identity["json"] == calc_md5(expected_canonical) # Verify the slow path WAS called mock_digest.assert_called_once() class BidiComponentStateCallbackTest(DeltaGeneratorTestCase): """Verify that per-state callbacks fire exclusively for their key.""" COMPONENT_NAME = "stateful_component" def setUp(self): super().setUp() # Set up a fresh component manager patched into the Runtime singleton. self.mock_component_manager = BidiComponentManager() self.runtime_patcher = patch.object( Runtime, "instance", return_value=MagicMock() ) self.mock_runtime = self.runtime_patcher.start() self.mock_runtime.return_value.bidi_component_registry = ( self.mock_component_manager ) # Register a minimal component definition (JS only is enough for backend tests). self.mock_component_manager.register( BidiComponentDefinition(name=self.COMPONENT_NAME, js="console.log('hi');") ) # Prepare per-event callback mocks. self.range_cb = MagicMock(name="range_cb") self.text_cb = MagicMock(name="text_cb") # First script run: render the component and capture its widget id. st._bidi_component( self.COMPONENT_NAME, on_range_change=self.range_cb, on_text_change=self.text_cb, ) self.component_id = ( self.get_delta_from_queue().new_element.bidi_component.id # type: ignore[attr-defined] ) # Sanity: no callbacks should have fired during initial render. self.range_cb.assert_not_called() self.text_cb.assert_not_called() def tearDown(self): super().tearDown() self.runtime_patcher.stop() # ------------------------------------------------------------------ # Helper utilities # ------------------------------------------------------------------ def _simulate_state_update(self, new_state: dict): """Trigger a faux frontend state update and run callbacks.""" ws = WidgetState(id=self.component_id) ws.json_value = json.dumps(new_state) self.script_run_ctx.session_state.on_script_will_rerun( WidgetStates(widgets=[ws]) ) # ------------------------------------------------------------------ # Tests # ------------------------------------------------------------------ def test_only_range_changes_invokes_only_range_callback(self): """Test that only the 'range' callback is invoked when only 'range' state changes.""" # Update just the "range" key. self._simulate_state_update({"range": 10}) self.range_cb.assert_called_once() self.text_cb.assert_not_called() def test_only_text_changes_invokes_only_text_callback(self): """Test that only the 'text' callback is invoked when only 'text' state changes.""" # Reset mock call history. self.range_cb.reset_mock() self.text_cb.reset_mock() # Update just the "text" key. self._simulate_state_update({"text": "hello"}) self.text_cb.assert_called_once() self.range_cb.assert_not_called() def test_both_keys_change_invokes_both_callbacks(self): """Test that both callbacks are invoked when both 'range' and 'text' states change.""" # Reset mock call history. self.range_cb.reset_mock() self.text_cb.reset_mock() # Update both keys simultaneously. self._simulate_state_update({"range": 77, "text": "world"}) self.range_cb.assert_called_once() self.text_cb.assert_called_once() class BidiComponentTriggerCallbackTest(DeltaGeneratorTestCase): """Verify that per-event *trigger* callbacks fire only for their event.""" COMPONENT_NAME = "trigger_component" # ------------------------------------------------------------------ # Test lifecycle helpers # ------------------------------------------------------------------ def setUp(self): super().setUp() # Patch a fresh component manager into the Runtime singleton so tests are isolated. self.component_manager = BidiComponentManager() self.runtime_patcher = patch.object( Runtime, "instance", return_value=MagicMock() ) self.mock_runtime = self.runtime_patcher.start() self.mock_runtime.return_value.bidi_component_registry = self.component_manager # Register a minimal JS-only component definition (enough for backend tests). self.component_manager.register( BidiComponentDefinition(name=self.COMPONENT_NAME, js="console.log('hi');") ) # Prepare mocks for per-event callbacks. self.range_trigger_cb = MagicMock(name="range_trigger_cb") self.text_trigger_cb = MagicMock(name="text_trigger_cb") self.button_cb = MagicMock(name="button_cb") # First script run: render the component and capture its widget id. st._bidi_component( self.COMPONENT_NAME, on_range_change=self.range_trigger_cb, on_text_change=self.text_trigger_cb, ) # Render a separate *button* widget that uses the classic trigger_value # mechanism so we can verify coexistence of multiple trigger sources. st.button("Click me!", on_click=self.button_cb) # After enqueuing both the component and the button, the button proto # is at the tail of the queue (index -1) and the component proto just # before that (index -2). self.button_id = self.get_delta_from_queue().new_element.button.id # type: ignore[attr-defined] self.component_id = ( self.get_delta_from_queue(-2).new_element.bidi_component.id # type: ignore[attr-defined] ) # Sanity: no callbacks should have fired during initial render. self.range_trigger_cb.assert_not_called() self.text_trigger_cb.assert_not_called() self.button_cb.assert_not_called() def tearDown(self): super().tearDown() # Stop Runtime.instance patcher started in setUp. self.runtime_patcher.stop() # ------------------------------------------------------------------ # Utility to simulate frontend trigger updates # ------------------------------------------------------------------ def _simulate_trigger_update(self, trigger_updates: dict[str, Any]): """Emulate the frontend firing one or more triggers. Parameters ---------- trigger_updates : Dict[str, Any] Mapping from *event name* to *payload* value. The payload will be JSON-serialized before being injected into the ``WidgetState`` protobuf. """ # Aggregator path: combine updates into a single payload updates = [ {"event": name, "value": payload} for name, payload in trigger_updates.items() ] payload = updates[0] if len(updates) == 1 else updates agg_id = _make_trigger_id(self.component_id, "events") ws = WidgetState(id=agg_id) ws.json_trigger_value = json.dumps(payload) widget_states = WidgetStates(widgets=[ws]) # Feed the simulated WidgetStates into Session State which will, in # turn, invoke the appropriate callbacks via ``_call_callbacks``. self.script_run_ctx.session_state.on_script_will_rerun(widget_states) def _simulate_button_click(self): """Simulate a user clicking the separate st.button widget.""" ws = WidgetState(id=self.button_id) ws.trigger_value = True widget_states = WidgetStates(widgets=[ws]) self.script_run_ctx.session_state.on_script_will_rerun(widget_states) # ------------------------------------------------------------------ # Tests # ------------------------------------------------------------------ def test_only_range_trigger_invokes_only_range_callback(self): """Updating only the ``range`` trigger should only call its callback.""" self._simulate_trigger_update({"range": 10}) self.range_trigger_cb.assert_called_once() self.text_trigger_cb.assert_not_called() # Value assertions via aggregator agg_id = _make_trigger_id(self.component_id, "events") assert self.script_run_ctx.session_state[agg_id] == [ {"event": "range", "value": 10} ] def test_only_text_trigger_invokes_only_text_callback(self): """Updating only the ``text`` trigger should only call its callback.""" self._simulate_trigger_update({"text": "hello"}) self.text_trigger_cb.assert_called_once() self.range_trigger_cb.assert_not_called() def test_both_triggers_fired_invokes_both_callbacks(self): """When *both* triggers fire simultaneously, *both* callbacks fire.""" self._simulate_trigger_update({"range": 77, "text": "world"}) self.range_trigger_cb.assert_called_once() self.text_trigger_cb.assert_called_once() # -------------------------------------------------------------- # Interactions involving *another* trigger widget (st.button) # -------------------------------------------------------------- def test_button_click_invokes_only_button_callback(self): """Clicking the separate st.button must not affect component triggers.""" self._simulate_button_click() self.button_cb.assert_called_once() self.range_trigger_cb.assert_not_called() self.text_trigger_cb.assert_not_called() # After a button click, the *previous* range trigger should have been # reset to ``None`` by SessionState._reset_triggers. agg_id = _make_trigger_id(self.component_id, "events") assert self.script_run_ctx.session_state[agg_id] is None self._simulate_trigger_update({"range": 10}) self.button_cb.assert_called_once() self.range_trigger_cb.assert_called_once() self.text_trigger_cb.assert_not_called() def test_button_and_component_trigger_both_fire(self): """Simultaneous component trigger + button click fires *all* callbacks.""" # Compose a single WidgetStates message that includes both updates. widget_states = WidgetStates() # Component trigger via aggregator for 'range' agg_id = _make_trigger_id(self.component_id, "events") ws_component = WidgetState(id=agg_id) ws_component.json_trigger_value = json.dumps({"event": "range", "value": 123}) widget_states.widgets.append(ws_component) # Button click ws_button = WidgetState(id=self.button_id) ws_button.trigger_value = True widget_states.widgets.append(ws_button) # Act self.script_run_ctx.session_state.on_script_will_rerun(widget_states) # Assert: all three callbacks should have fired accordingly. self.range_trigger_cb.assert_called_once() self.button_cb.assert_called_once() # text trigger remains untouched self.text_trigger_cb.assert_not_called() def test_handle_deserialize_with_none_input(self): """Test handle_deserialize returns None when input is None.""" # Get the handle_deserialize function by creating an instance # and accessing the function through the component creation process deserializer = self._get_handle_deserialize_function() result = deserializer(None) assert result is None def test_handle_deserialize_with_valid_json_strings(self): """Test handle_deserialize correctly parses valid JSON strings.""" deserializer = self._get_handle_deserialize_function() # Test various valid JSON values test_cases = [ ("null", None), ("true", True), ("false", False), ("123", 123), ("-45.67", -45.67), ('"hello"', "hello"), ('"test string"', "test string"), ('{"key": "value"}', {"key": "value"}), ("[1, 2, 3]", [1, 2, 3]), ('{"nested": {"data": [1, 2]}}', {"nested": {"data": [1, 2]}}), ] for json_str, expected in test_cases: result = deserializer(json_str) assert result == expected, ( f"Failed for input {json_str!r}: expected {expected!r}, got {result!r}" ) def test_handle_deserialize_with_invalid_json_returns_string(self): """Test handle_deserialize returns string as-is when JSON parsing fails.""" deserializer = self._get_handle_deserialize_function() # Test various non-JSON strings that should be returned as-is test_cases = [ "hello world", "not json", "123abc", "true but not quite", "{not valid json}", "[1, 2, 3", # Missing closing bracket '{"incomplete": ', # Incomplete JSON "simple text", "user input value", "component_state_value", ] for invalid_json in test_cases: result = deserializer(invalid_json) assert result == invalid_json, ( f"Failed for input {invalid_json!r}: expected {invalid_json!r}, got {result!r}" ) def test_handle_deserialize_with_empty_and_whitespace_strings(self): """Test handle_deserialize handles empty and whitespace strings correctly.""" deserializer = self._get_handle_deserialize_function() # Empty and whitespace strings should be returned as-is since they're not valid JSON test_cases = [ "", # Empty string " ", # Single space " ", # Multiple spaces "\t", # Tab "\n", # Newline "\r\n", # Windows line ending " \t\n ", # Mixed whitespace ] for whitespace_str in test_cases: result = deserializer(whitespace_str) assert result == whitespace_str, ( f"Failed for input {whitespace_str!r}: expected {whitespace_str!r}, got {result!r}" ) def test_handle_deserialize_with_edge_case_strings(self): """Test handle_deserialize with edge case string inputs.""" deserializer = self._get_handle_deserialize_function() # Test cases that should be returned as strings (not valid JSON) string_cases = [ "undefined", # Common JS value "null_but_not", # Looks like null but isn't "True", # Python True (capital T) "False", # Python False (capital F) '"unclosed string', # Malformed JSON string 'single"quote', # Mixed quotes "emoji πŸ˜€", # Unicode content "special chars: àÑÒãÀΓ₯", # Accented characters ] for edge_case in string_cases: result = deserializer(edge_case) assert result == edge_case, ( f"Failed for input {edge_case!r}: expected {edge_case!r}, got {result!r}" ) # Test cases that are valid JSON and should be parsed json_cases = [ ("0", 0), # Valid JSON number ] for json_str, expected in json_cases: result = deserializer(json_str) assert result == expected, ( f"Failed for input {json_str!r}: expected {expected!r}, got {result!r}" ) # Non-standard JSON values: Python's json module accepts these and # returns float representations even though they're not part of the # official JSON specification. nonstandard_cases = [ ("NaN", math.isnan), ("Infinity", lambda v: math.isinf(v) and v > 0), ("-Infinity", lambda v: math.isinf(v) and v < 0), ] for json_str, predicate in nonstandard_cases: result = deserializer(json_str) assert isinstance(result, float), ( f"Failed for input {json_str!r}: expected float, got {type(result).__name__}: {result!r}" ) assert predicate(result), ( f"Failed for input {json_str!r}: float did not meet predicate, got {result!r}" ) def _get_handle_deserialize_function(self): """Helper method to extract the handle_deserialize function for testing.""" # We need to access the handle_deserialize function that's defined inside # the component creation process. Since it's a local function, we'll # simulate the creation process or create a standalone version for testing. def handle_deserialize(s: str | None) -> Any: """Standalone version of the handle_deserialize function for testing.""" if s is None: return None try: return json.loads(s) except json.JSONDecodeError: return s return handle_deserialize def test_string_values_work_in_trigger_updates(self): """Integration test: verify string values work properly in trigger updates.""" # Test that string values that aren't valid JSON are handled correctly # in the context of actual trigger updates widget_states = WidgetStates() # Test with a plain string value (not valid JSON) ws_component = WidgetState(id=_make_trigger_id(self.component_id, "events")) ws_component.json_trigger_value = json.dumps( {"event": "text", "value": "plain string value"} ) widget_states.widgets.append(ws_component) # Process the widget states self.script_run_ctx.session_state.on_script_will_rerun(widget_states) # Verify the trigger value is accessible and equals the original object (wrapped in list) text_trigger_id = _make_trigger_id(self.component_id, "events") trigger_value = self.script_run_ctx.session_state[text_trigger_id] assert trigger_value == [{"event": "text", "value": "plain string value"}] # Verify the callback was called self.text_trigger_cb.assert_called_once() def test_mixed_json_and_string_values_in_triggers(self): """Integration test: verify both JSON and string values work together.""" widget_states = WidgetStates() # Combine both triggers into a single aggregator payload list agg_id = _make_trigger_id(self.component_id, "events") ws_both = WidgetState(id=agg_id) ws_both.json_trigger_value = json.dumps( [ {"event": "range", "value": 42}, {"event": "text", "value": "user input text"}, ] ) widget_states.widgets.append(ws_both) # Process the widget states self.script_run_ctx.session_state.on_script_will_rerun(widget_states) # Verify both values are correctly deserialized agg_id = _make_trigger_id(self.component_id, "events") agg_value = self.script_run_ctx.session_state[agg_id] assert isinstance(agg_value, list) by_event = {item["event"]: item["value"] for item in agg_value} assert by_event["range"] == 42 assert by_event["text"] == "user input text" # Verify both callbacks were called self.range_trigger_cb.assert_called_once() self.text_trigger_cb.assert_called_once() def test_empty_string_json_trigger_value_does_not_crash(self): """Test that an empty string json_trigger_value doesn't cause issues.""" # Simulate a trigger update with an empty string widget_states = WidgetStates() ws_component = WidgetState(id=_make_trigger_id(self.component_id, "events")) ws_component.json_trigger_value = json.dumps({"event": "range", "value": ""}) widget_states.widgets.append(ws_component) # Process the widget states self.script_run_ctx.session_state.on_script_will_rerun(widget_states) # Access the trigger value - this should work without throwing an exception range_id = _make_trigger_id(self.component_id, "events") trigger_value = self.script_run_ctx.session_state[range_id] # The trigger value should be a list with one object with empty string value assert trigger_value == [{"event": "range", "value": ""}] # The callback should have been called since we have a non-None value self.range_trigger_cb.assert_called_once() def test_whitespace_json_trigger_value_preserves_whitespace(self): """Test that whitespace-only json_trigger_value preserves the whitespace.""" # Simulate a trigger update with whitespace widget_states = WidgetStates() ws_component = WidgetState(id=_make_trigger_id(self.component_id, "events")) ws_component.json_trigger_value = json.dumps({"event": "range", "value": " "}) widget_states.widgets.append(ws_component) # Process the widget states self.script_run_ctx.session_state.on_script_will_rerun(widget_states) # Access the trigger value range_id = _make_trigger_id(self.component_id, "events") trigger_value = self.script_run_ctx.session_state[range_id] # The trigger value should preserve the whitespace within the object assert trigger_value == [{"event": "range", "value": " "}] # The callback should have been called since we have a non-None value self.range_trigger_cb.assert_called_once() def test_deserializer_lambda_handles_edge_cases(self): """Test the deserializer lambda function directly with various edge cases.""" # This test is now updated to test the new handle_deserialize function deserializer = self._get_handle_deserialize_function() # Test cases that should work with the new deserializer assert deserializer(None) is None assert deserializer("null") is None assert deserializer('"hello"') == "hello" assert deserializer("123") == 123 assert deserializer('{"key": "value"}') == {"key": "value"} # Test string values that aren't JSON - these should return as strings assert deserializer("") == "" assert deserializer(" ") == " " assert deserializer(" ") == " " assert deserializer("\n") == "\n" assert deserializer("\t") == "\t" assert deserializer("plain text") == "plain text" assert deserializer("not json") == "not json" # All of these should work without raising JSONDecodeError test_cases = ["", " ", " ", "\n", "\t", "plain text", "user input"] for s in test_cases: assert deserializer(s) == s
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_bidi_component.py", "license": "Apache License 2.0", "lines": 1595, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/components/v2/test_bidi_presentation.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import copy from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock, patch import pytest from streamlit.components.v2.presentation import make_bidi_component_presenter from streamlit.errors import StreamlitAPIException from streamlit.runtime.state import SessionState class _FakeWStates: def __init__(self) -> None: self.widget_metadata: dict[str, Any] = {} self._payloads: dict[str, Any] = {} def __getitem__(self, k: str) -> Any: # emulate WStates __getitem__ if k not in self._payloads: raise KeyError(k) return self._payloads[k] class _FakeSession: def __init__(self) -> None: self._new_widget_state = _FakeWStates() def test_bidi_presenter_merges_events_when_present() -> None: """Test that the presenter correctly merges event payloads into the base state.""" ss = _FakeSession() agg_id = "$$_internal__wid__events" presenter = make_bidi_component_presenter(agg_id) ss._new_widget_state.widget_metadata[agg_id] = SimpleNamespace( value_type="json_trigger_value" ) ss._new_widget_state._payloads[agg_id] = [ {"event": "foo", "value": True}, {"event": "bar", "value": 123}, ] base = {"alpha": 1} out = presenter(base, ss) assert dict(out) == {"alpha": 1, "foo": True, "bar": 123} def test_bidi_presenter_handles_non_list_payload() -> None: """Test that the presenter can handle a single, non-list event payload.""" ss = _FakeSession() agg_id = "$$_internal__wid__events" presenter = make_bidi_component_presenter(agg_id) ss._new_widget_state.widget_metadata[agg_id] = SimpleNamespace( value_type="json_trigger_value" ) ss._new_widget_state._payloads[agg_id] = {"event": "foo", "value": "x"} base = {} out = presenter(base, ss) assert dict(out) == {"foo": "x"} def test_bidi_presenter_returns_base_on_missing_meta_or_wrong_type() -> None: """Test that the presenter returns the base value if metadata is missing or incorrect.""" ss = _FakeSession() agg_id = "$$_internal__wid__events" presenter = make_bidi_component_presenter(agg_id) base = {"value": {"beta": 2}} # No metadata assert presenter(base, ss) == base # Wrong value type ss._new_widget_state.widget_metadata[agg_id] = SimpleNamespace(value_type="json") assert presenter(base, ss) == base def test_bidi_presenter_returns_base_on_non_canonical_state_shape() -> None: """Test that the presenter returns the base value if the state shape is not canonical.""" ss = _FakeSession() agg_id = "$$_internal__wid__events" presenter = make_bidi_component_presenter(agg_id) ss._new_widget_state.widget_metadata[agg_id] = SimpleNamespace( value_type="json_trigger_value" ) base = {"not_value": {}} assert presenter(base, ss) == base def test_setitem_disallows_setting_created_widget(): """Test that __setitem__ disallows setting a created widget.""" mock_session_state = MagicMock(spec=SessionState) mock_session_state._key_id_mapper = MagicMock() mock_session_state._key_id_mapper.get_key_from_id.return_value = "test_key" mock_session_state._new_widget_state = MagicMock() mock_session_state._new_widget_state.widget_metadata.get.return_value = MagicMock( value_type="json_trigger_value" ) mock_ctx = MagicMock() mock_ctx.widget_ids_this_run = {"test_component_id"} mock_ctx.form_ids_this_run = set() presenter = make_bidi_component_presenter( aggregator_id="test_aggregator_id", component_id="test_component_id", ) write_through_dict = presenter({}, mock_session_state) with patch( "streamlit.components.v2.presentation.get_script_run_ctx", return_value=mock_ctx, ): with pytest.raises(StreamlitAPIException) as e: write_through_dict["value"] = "new_value" assert ( "`st.session_state.test_key.value` cannot be modified after the component" in str(e.value) ) def test_delitem_disallows_deleting_from_created_widget(): """Test that __delitem__ disallows deleting from a created widget.""" mock_session_state = MagicMock(spec=SessionState) mock_session_state._key_id_mapper = MagicMock() mock_session_state._key_id_mapper.get_key_from_id.return_value = "test_key" mock_session_state._new_widget_state = MagicMock() mock_session_state._new_widget_state.widget_metadata.get.return_value = MagicMock( value_type="json_trigger_value" ) mock_ctx = MagicMock() mock_ctx.widget_ids_this_run = {"test_component_id"} mock_ctx.form_ids_this_run = set() presenter = make_bidi_component_presenter( aggregator_id="test_aggregator_id", component_id="test_component_id", ) write_through_dict = presenter({"value": "old_value"}, mock_session_state) with patch( "streamlit.components.v2.presentation.get_script_run_ctx", return_value=mock_ctx, ): with pytest.raises(StreamlitAPIException) as e: del write_through_dict["value"] assert ( "`st.session_state.test_key.value` cannot be modified after the component" in str(e.value) ) def test_setitem_disallows_setting_widget_in_form(): """Test that __setitem__ disallows setting a widget in a form.""" mock_session_state = MagicMock(spec=SessionState) mock_session_state._key_id_mapper = MagicMock() mock_session_state._key_id_mapper.get_key_from_id.return_value = "test_key" mock_session_state._new_widget_state = MagicMock() mock_session_state._new_widget_state.widget_metadata.get.return_value = MagicMock( value_type="json_trigger_value" ) mock_ctx = MagicMock() mock_ctx.widget_ids_this_run = set() mock_ctx.form_ids_this_run = {"test_key"} presenter = make_bidi_component_presenter( aggregator_id="test_aggregator_id", component_id="test_component_id", ) write_through_dict = presenter({}, mock_session_state) with patch( "streamlit.components.v2.presentation.get_script_run_ctx", return_value=mock_ctx, ): with pytest.raises(StreamlitAPIException) as e: write_through_dict["value"] = "new_value" assert ( "`st.session_state.test_key.value` cannot be modified after the component" in str(e.value) ) def test_setitem_allows_setting_before_widget_creation(): """Test that __setitem__ allows setting state before widget creation.""" mock_session_state = MagicMock(spec=SessionState) mock_session_state._key_id_mapper = MagicMock() mock_session_state._key_id_mapper.get_key_from_id.return_value = "test_key" mock_session_state._new_widget_state = MagicMock() mock_session_state._new_widget_state.widget_metadata.get.return_value = MagicMock( value_type="json_trigger_value" ) mock_ctx = MagicMock() mock_ctx.widget_ids_this_run = set() mock_ctx.form_ids_this_run = set() presenter = make_bidi_component_presenter( aggregator_id="test_aggregator_id", component_id="test_component_id", ) write_through_dict = presenter({}, mock_session_state) with patch( "streamlit.components.v2.presentation.get_script_run_ctx", return_value=mock_ctx, ): try: write_through_dict["value"] = "new_value" except StreamlitAPIException as e: pytest.fail(f"Setting state before creation raised an exception: {e}") def test_deepcopy_returns_self(): """Test that deepcopy returns the same object.""" mock_session_state = MagicMock(spec=SessionState) mock_session_state._key_id_mapper = MagicMock() mock_session_state._new_widget_state = MagicMock() mock_session_state._new_widget_state.widget_metadata.get.return_value = MagicMock( value_type="json_trigger_value" ) presenter = make_bidi_component_presenter( aggregator_id="test_aggregator_id", component_id="test_component_id", ) write_through_dict = presenter({}, mock_session_state) copied_dict = copy.deepcopy(write_through_dict) assert write_through_dict is copied_dict
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_bidi_presentation.py", "license": "Apache License 2.0", "lines": 202, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/runtime/state/presentation.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Any, Final from streamlit.logger import get_logger _LOGGER: Final = get_logger(__name__) if TYPE_CHECKING: from streamlit.runtime.state.session_state import SessionState def apply_presenter( session_state: SessionState, widget_id: str, base_value: Any ) -> Any: """Return the user-visible value for a widget if it has a ``presenter``. If the widget's metadata defines a ``presenter`` callable, it is used to transform the stored value into its presentation form. Any exception raised while resolving metadata or invoking the presenter is swallowed and ``base_value`` is returned, so presentation never interferes with core behavior. Notes ----- Presentation is applied exclusively for user-facing access paths such as: - `st.session_state[... ]` via `SessionState.__getitem__` - `SessionState.filtered_state` Internal serialization paths (for example `WStates.as_widget_states()` and `SessionState.get_widget_states()`) must operate on base (unpresented) values to ensure stable and lossless serialization. Do not use `apply_presenter` in serialization code paths. Parameters ---------- session_state : SessionState The current session state object that holds widget state and metadata. widget_id : str The identifier of the widget whose value is being presented. base_value : Any The raw value stored for the widget. Returns ------- Any The value that should be shown to the user. """ try: meta = session_state._get_widget_metadata(widget_id) presenter = getattr(meta, "presenter", None) if meta is not None else None if presenter is None: return base_value # Ensure the presenter is callable to avoid silently failing on a # TypeError when attempting to invoke a non-callable value. if not callable(presenter): _LOGGER.warning( "Widget '%s' has a non-callable presenter (%r); returning base value.", widget_id, presenter, ) return base_value try: return presenter(base_value, session_state) except Exception: return base_value except Exception: # If metadata is unavailable or any other error occurs, degrade gracefully. return base_value
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/runtime/state/presentation.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/runtime/state/test_presentation.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from types import SimpleNamespace from typing import Any from streamlit.components.v2.bidi_component.main import _make_trigger_id from streamlit.components.v2.presentation import make_bidi_component_presenter from streamlit.runtime.state.common import WidgetMetadata from streamlit.runtime.state.presentation import apply_presenter from streamlit.runtime.state.session_state import SessionState, Value class _FakeWStates: def __init__(self) -> None: self.widget_metadata: dict[str, Any] = {} class _FakeSession: def __init__(self) -> None: self._new_widget_state = _FakeWStates() def _get_widget_metadata(self, widget_id: str) -> WidgetMetadata[Any] | None: return self._new_widget_state.widget_metadata.get(widget_id) def test_apply_presenter_returns_base_when_no_meta() -> None: """Return base value unchanged when widget metadata is missing.""" ss = _FakeSession() base = {"value": 1} out = apply_presenter(ss, "wid", base) assert out is base def test_apply_presenter_returns_base_when_no_presenter() -> None: """Return base value unchanged when metadata has no presenter.""" ss = _FakeSession() ss._new_widget_state.widget_metadata["wid"] = SimpleNamespace() base = [1, 2, 3] out = apply_presenter(ss, "wid", base) assert out is base def test_apply_presenter_applies_presenter() -> None: """Apply the registered presenter to the base value.""" def _presenter(base: Any, _ss: Any) -> Any: return {"presented": base} ss = _FakeSession() ss._new_widget_state.widget_metadata["wid"] = SimpleNamespace(presenter=_presenter) base = {"value": 123} out = apply_presenter(ss, "wid", base) assert out == {"presented": {"value": 123}} def test_apply_presenter_swallows_presenter_errors() -> None: """Return base value unchanged if presenter raises an exception.""" def _boom(_base: Any, _ss: Any) -> Any: raise RuntimeError("boom") ss = _FakeSession() ss._new_widget_state.widget_metadata["wid"] = SimpleNamespace(presenter=_boom) base = "hello" out = apply_presenter(ss, "wid", base) assert out is base def test_presenter_applied_once_via_getitem_and_filtered_state() -> None: """Presenter must be applied exactly once for both __getitem__ and filtered_state. We simulate a widget with a user key mapping and attach a presenter that wraps the base value in a dict. Double application would produce nested wrapping. """ ss = SessionState() # Simulate a widget with element id and user key mapping widget_id = "$$ID-abc-ukey" user_key = "ukey" # Register metadata with a no-op deserializer/serializer for a simple string meta = WidgetMetadata[str]( id=widget_id, deserializer=lambda v: v, serializer=lambda v: v, value_type="string_value", ) ss._set_widget_metadata(meta) ss._set_key_widget_mapping(widget_id, user_key) # Set the underlying widget value in new widget state ss._new_widget_state.set_from_value(widget_id, "base") # Install a presenter that wraps once def _wrap_once(base: Any, _ss: Any) -> Any: return {"presented": base} # Attach presenter to metadata store ss._new_widget_state.widget_metadata[widget_id] = SimpleNamespace( id=widget_id, deserializer=meta.deserializer, serializer=meta.serializer, value_type=meta.value_type, presenter=_wrap_once, ) # Access via __getitem__ using the widget id; should apply once got = ss[widget_id] assert got == {"presented": "base"} # Access via filtered_state using the user key; should apply once filtered = ss.filtered_state assert filtered[user_key] == {"presented": "base"} def test_get_widget_states_uses_base_value_not_presented() -> None: """Serialized widget states must contain base (unpresented) values. This ensures presentation is only applied for user-facing access via `st.session_state[...]` and `filtered_state`, while serialization stays lossless and stable. """ ss = SessionState() # Create widget metadata for a simple string and register mapping. widget_id = "$$ID-abc-ukey" user_key = "ukey" meta = WidgetMetadata[str]( id=widget_id, deserializer=lambda v: v, serializer=lambda v: v, value_type="string_value", ) ss._set_widget_metadata(meta) ss._set_key_widget_mapping(widget_id, user_key) # Underlying base value stored in widget state. base_value = "raw" ss._new_widget_state.set_from_value(widget_id, base_value) # Presenter that would wrap the base value if applied. def _wrap(base: Any, _ss: Any) -> Any: return {"presented": base} # Attach presenter on metadata store (simulating element registration that # enriches the metadata entry). ss._new_widget_state.widget_metadata[widget_id] = SimpleNamespace( id=widget_id, deserializer=meta.deserializer, serializer=meta.serializer, value_type=meta.value_type, presenter=_wrap, ) # Verify that user-facing access applies presentation. assert ss[widget_id] == {"presented": base_value} # Now get serialized widget states; these should contain the base value # via the `string_value` field and not the presented wrapper. states = ss.get_widget_states() assert len(states) == 1 st = states[0] # Ensure we serialized as string_value and not JSON or other wrappers assert st.WhichOneof("value") == "string_value" assert st.string_value == base_value def test_filtered_state_includes_keyed_element_when_not_internal() -> None: """filtered_state includes user key for keyed element ids when not internal.""" ss = SessionState() widget_id = "$$ID-abc-ukey" user_key = "ukey" # Minimal metadata and value meta = WidgetMetadata[str]( id=widget_id, deserializer=lambda v: v, serializer=lambda v: v, value_type="string_value", ) ss._set_widget_metadata(meta) ss._new_widget_state.set_from_value(widget_id, "base") ss._set_key_widget_mapping(widget_id, user_key) filtered = ss.filtered_state assert user_key in filtered assert filtered[user_key] == "base" def test_filtered_state_excludes_keyed_element_when_internal(monkeypatch) -> None: """filtered_state excludes entries when _is_internal_key(k) is True for the id.""" import streamlit.runtime.state.session_state as ss_mod ss = SessionState() widget_id = "$$ID-internal-ukey" user_key = "ukey" meta = WidgetMetadata[str]( id=widget_id, deserializer=lambda v: v, serializer=lambda v: v, value_type="string_value", ) ss._set_widget_metadata(meta) ss._new_widget_state.set_from_value(widget_id, "base") ss._set_key_widget_mapping(widget_id, user_key) # Patch _is_internal_key to treat this widget_id as internal original = ss_mod._is_internal_key monkeypatch.setattr( ss_mod, "_is_internal_key", lambda k: True if k == widget_id else original(k), raising=True, ) filtered = ss.filtered_state assert user_key not in filtered def test_session_state_merges_ccv2_trigger_values_via_presenter() -> None: """Integration: SessionState uses presenter to merge CCv2 trigger values. We simulate a CCv2 component with a persistent state widget and an internal trigger aggregator. The component registers a presenter via the shared facade. We then assert that SessionState.filtered_state (user-facing view) returns the persistent state merged with the latest trigger values, while the underlying stored state remains unmodified. """ session_state = SessionState() # Simulate a component persistent state widget with user key mapping component_id = "$$ID-bidi_component-my_component" user_key = "my_component" session_state._key_id_mapper[user_key] = component_id # Store base persistent state as flat mapping base_persistent = {"alpha": 1} session_state._new_widget_state.states[component_id] = Value(base_persistent) session_state._new_widget_state.widget_metadata[component_id] = WidgetMetadata( id=component_id, deserializer=lambda x: x, serializer=lambda x: x, value_type="json_value", ) # Create trigger aggregator and payloads aggregator_id = _make_trigger_id(component_id, "events") session_state._new_widget_state.widget_metadata[aggregator_id] = WidgetMetadata( id=aggregator_id, deserializer=lambda x: x, serializer=lambda x: x, value_type="json_trigger_value", ) session_state._new_widget_state.states[aggregator_id] = Value( [ {"event": "foo", "value": True}, {"event": "bar", "value": 123}, ] ) # Attach presenter (what bidi_component.py does during registration) presenter = make_bidi_component_presenter(aggregator_id) meta = session_state._new_widget_state.widget_metadata[component_id] object.__setattr__(meta, "presenter", presenter) # User-visible filtered state should show merged view merged = session_state.filtered_state[user_key] assert dict(merged) == {"alpha": 1, "foo": True, "bar": 123} # Underlying stored state remains unmodified assert session_state._new_widget_state.states[component_id].value is base_persistent def test_session_state_presenter_errors_degrade_gracefully() -> None: """Integration: presenter exceptions should not break SessionState access. If a presenter raises, SessionState should fall back to the base value without propagating exceptions to the caller. """ session_state = SessionState() component_id = "$$ID-bidi_component-err_component" user_key = "err_component" session_state._key_id_mapper[user_key] = component_id base_persistent: dict[str, Any] = {"value": {"x": 1}} session_state._new_widget_state.states[component_id] = Value(base_persistent) meta = WidgetMetadata( id=component_id, deserializer=lambda x: x, serializer=lambda x: x, value_type="json_value", ) object.__setattr__( meta, "presenter", lambda _b, _s: exec('raise RuntimeError("boom")') ) session_state._new_widget_state.widget_metadata[component_id] = meta # Access should not raise; should return base value instead assert session_state.filtered_state[user_key] == base_persistent def test_bidi_presenter_state_overrides_duplicate_keys() -> None: """State must override trigger values on duplicate keys. This verifies the merge precedence documented in the presenter and in BidiComponentResult: triggers are surfaced first, but persistent state wins for duplicate keys. """ class _FakeWStates2: def __init__(self) -> None: self.widget_metadata: dict[str, Any] = {} self._payloads: dict[str, Any] = {} def __getitem__(self, k: str) -> Any: # emulate __getitem__ for payloads if k not in self._payloads: raise KeyError(k) return self._payloads[k] class _FakeSession2: def __init__(self) -> None: self._new_widget_state = _FakeWStates2() ss = _FakeSession2() agg_id = "$$__internal__events" presenter = make_bidi_component_presenter(agg_id) ss._new_widget_state.widget_metadata[agg_id] = SimpleNamespace( value_type="json_trigger_value" ) ss._new_widget_state._payloads[agg_id] = [ {"event": "shared", "value": "trigger"}, {"event": "only_trigger", "value": 1}, ] base = {"shared": "state", "only_state": 2} out = presenter(base, ss) assert dict(out) == { "shared": "state", "only_trigger": 1, "only_state": 2, }
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/runtime/state/test_presentation.py", "license": "Apache License 2.0", "lines": 285, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/web/server/bidi_component_request_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Serve static assets for Custom Components v2. This module defines a Tornado ``RequestHandler`` that serves static files for Custom Components v2 from their registered component directories. Requests are resolved safely within the component's root to avoid directory traversal and are served with appropriate content type and cache headers. CORS headers are applied based on the server configuration. """ from __future__ import annotations import os from typing import TYPE_CHECKING, Final, cast import tornado.web import streamlit.web.server.routes from streamlit.logger import get_logger from streamlit.web.server.component_file_utils import ( build_safe_abspath, guess_content_type, ) if TYPE_CHECKING: from streamlit.components.v2.component_manager import BidiComponentManager _LOGGER: Final = get_logger(__name__) class BidiComponentRequestHandler(tornado.web.RequestHandler): """Request handler for serving Custom Components v2 static assets. The handler resolves a requested path to a registered component's asset within its component root, writes the file contents to the response, and sets appropriate ``Content-Type`` and cache headers. If the component or asset cannot be found, a suitable HTTP status is returned. """ def initialize(self, component_manager: BidiComponentManager) -> None: """Initialize the handler with the given component manager. Parameters ---------- component_manager : BidiComponentManager Manager used to look up registered components and their root paths. """ self._component_manager = component_manager def get(self, path: str) -> None: """Serve a component asset for the given URL path. The first path segment is interpreted as the component name. The rest of the path is resolved to a file within that component's root directory. If the file exists and is readable, its bytes are written to the response and the ``Content-Type`` header is set based on the file type. Parameters ---------- path : str Request path in the form ``"<component_name>/<relative_file>"``. Notes ----- This method writes directly to the response and sets appropriate HTTP status codes on error (``404`` for missing components/files, ``400`` for unsafe paths). """ parts = path.split("/") component_name = parts[0] component_def = self._component_manager.get(component_name) if component_def is None: self.write("not found") self.set_status(404) return # Get the component path from the component manager component_path = self._component_manager.get_component_path(component_name) if component_path is None: self.write("not found") self.set_status(404) return # Build a safe absolute path within the component root filename = "/".join(parts[1:]) # If no file segment is provided (e.g. only component name or trailing slash), # treat as not found rather than attempting to open a directory. if not filename or filename.endswith("/"): self.write("not found") self.set_status(404) return abspath = build_safe_abspath(component_path, filename) if abspath is None: self.write("Bad Request") self.set_status(400) return # If the resolved path is a directory, return 404 not found. if os.path.isdir(abspath): self.write("not found") self.set_status(404) return try: with open(abspath, "rb") as file: contents = file.read() except OSError: sanitized_abspath = abspath.replace("\n", "").replace("\r", "") _LOGGER.exception( "BidiComponentRequestHandler: GET %s read error", sanitized_abspath ) self.write("read error") self.set_status(404) return self.write(contents) self.set_header("Content-Type", guess_content_type(abspath)) self.set_extra_headers(path) def set_extra_headers(self, path: str) -> None: """Disable cache for HTML files. We assume other assets like JS and CSS are suffixed with their hash, so they can be cached indefinitely. """ if path.endswith(".html"): self.set_header("Cache-Control", "no-cache") else: self.set_header("Cache-Control", "public") def set_default_headers(self) -> None: """Set default CORS headers based on server configuration. If cross-origin requests are fully allowed, ``Access-Control-Allow- Origin`` is set to ``"*"``. Otherwise, if the request ``Origin`` header is an allowed origin, the header is echoed back. """ if streamlit.web.server.routes.allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif streamlit.web.server.routes.is_allowed_origin( origin := self.request.headers.get("Origin") ): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def options(self) -> None: """Handle preflight CORS requests. Returns ------- None Responds with HTTP ``204 No Content`` to indicate that the actual request can proceed. """ self.set_status(204) self.finish() @staticmethod def get_url(file_id: str) -> str: """Return the URL for a component asset identified by ``file_id``. Parameters ---------- file_id : str Component file identifier (typically a relative path or hashed filename). Returns ------- str Relative URL path for the resource, to be joined with the server base URL. Examples -------- >>> BidiComponentRequestHandler.get_url("my_component/main.js") '_stcore/bidi-components/my_component/main.js' """ return f"_stcore/bidi-components/{file_id}"
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/web/server/bidi_component_request_handler.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/web/server/component_file_utils.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for safely resolving component asset paths and content types. These helpers are used by server handlers to construct safe absolute paths for component files and to determine the appropriate ``Content-Type`` header for responses. Path resolution prevents directory traversal by normalizing and checking real paths against a component's root directory. """ from __future__ import annotations import mimetypes import os from typing import Final from streamlit.path_security import is_unsafe_path_pattern _OCTET_STREAM: Final[str] = "application/octet-stream" def build_safe_abspath(component_root: str, relative_url_path: str) -> str | None: r"""Build an absolute path inside ``component_root`` if safe. The function first validates that ``relative_url_path`` does not contain dangerous patterns using :func:`~streamlit.path_security.is_unsafe_path_pattern`, then joins it with ``component_root`` and resolves symlinks. Returns ``None`` if the path is rejected by security checks or escapes the root. Parameters ---------- component_root : str Absolute path to the component's root directory. relative_url_path : str Relative URL path from the component root to the requested file. Must be a simple relative path without dangerous patterns. Returns ------- str or None The resolved absolute path if it passes all validation and stays within ``component_root``; otherwise ``None``. """ # See is_unsafe_path_pattern() for security details. if is_unsafe_path_pattern(relative_url_path): return None root_real = os.path.realpath(component_root) candidate = os.path.normpath(os.path.join(root_real, relative_url_path)) candidate_real = os.path.realpath(candidate) try: # Ensure the candidate stays within the real component root if os.path.commonpath([root_real, candidate_real]) != root_real: return None except ValueError: # On some platforms, commonpath can raise if drives differ; treat as forbidden. return None return candidate_real def guess_content_type(abspath: str) -> str: """Guess the HTTP ``Content-Type`` for a file path. This logic mirrors Tornado's ``StaticFileHandler`` by respecting encoding metadata from ``mimetypes.guess_type`` and falling back to ``application/octet-stream`` when no specific type can be determined. Parameters ---------- abspath : str Absolute file path used for type detection (only the suffix matters). Returns ------- str Guessed content type string suitable for the ``Content-Type`` header. """ mime_type, encoding = mimetypes.guess_type(abspath) # per RFC 6713, use the appropriate type for a gzip compressed file if encoding == "gzip": return "application/gzip" # As of 2015-07-21 there is no bzip2 encoding defined at # http://www.iana.org/assignments/media-types/media-types.xhtml # So for that (and any other encoding), use octet-stream. if encoding is not None: return _OCTET_STREAM if mime_type is not None: return mime_type # if mime_type not detected, use application/octet-stream return _OCTET_STREAM
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/web/server/component_file_utils.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/web/server/bidi_component_request_handler_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import tempfile from pathlib import Path from unittest import mock import tornado.testing import tornado.web from streamlit.components.v2.component_manager import BidiComponentManager from streamlit.components.v2.manifest_scanner import ComponentConfig, ComponentManifest from streamlit.web.server.bidi_component_request_handler import ( BidiComponentRequestHandler, ) from tests.testutil import patch_config_options class BidiComponentRequestHandlerTest(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: self.component_manager = BidiComponentManager() self.temp_dir = tempfile.TemporaryDirectory() super().setUp() # Create a fake package root with a component asset_dir self.package_root = Path(self.temp_dir.name) / "pkgroot" self.package_root.mkdir(parents=True, exist_ok=True) self.component_assets_dir = self.package_root / "test_component" self.component_assets_dir.mkdir(parents=True, exist_ok=True) # Create assets (self.component_assets_dir / "index.js").write_text( "console.log('test component');" ) (self.component_assets_dir / "index.html").write_text( "<div>Test Component</div>" ) (self.component_assets_dir / "styles.css").write_text("div { color: red; }") # Create a subdirectory to validate directory path handling (self.component_assets_dir / "subdir").mkdir(parents=True, exist_ok=True) # Register from a manifest that declares the asset_dir manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ ComponentConfig(name="test_component", asset_dir="test_component") ], ) self.component_manager.register_from_manifest(manifest, self.package_root) def tearDown(self) -> None: super().tearDown() self.temp_dir.cleanup() def get_app(self) -> tornado.web.Application: return tornado.web.Application( [ ( r"/_stcore/bidi-components/(.*)", BidiComponentRequestHandler, {"component_manager": self.component_manager}, ) ] ) def test_get_component_file(self) -> None: # JS should be accessible response = self.fetch("/_stcore/bidi-components/pkg.test_component/index.js") assert response.code == 200 assert response.body.decode() == "console.log('test component');" # HTML files should be accessible response = self.fetch("/_stcore/bidi-components/pkg.test_component/index.html") assert response.code == 200 assert response.body.decode() == "<div>Test Component</div>" # CSS should be accessible response = self.fetch("/_stcore/bidi-components/pkg.test_component/styles.css") assert response.code == 200 assert response.body.decode() == "div { color: red; }" def test_component_not_found(self) -> None: response = self.fetch("/_stcore/bidi-components/nonexistent_component/index.js") assert response.code == 404 response = self.fetch( "/_stcore/bidi-components/pkg.nonexistent_component/index.js" ) assert response.code == 404 def test_disallow_path_traversal(self) -> None: # Attempt path traversal attack response = self.fetch( "/_stcore/bidi-components/pkg.test_component/../../../etc/passwd" ) assert response.code == 400 def test_file_not_found_in_component_dir(self) -> None: response = self.fetch( "/_stcore/bidi-components/pkg.test_component/nonexistent.js" ) assert response.code == 404 def test_get_url(self) -> None: url = BidiComponentRequestHandler.get_url("pkg.test_component/index.js") assert url == "_stcore/bidi-components/pkg.test_component/index.js" def test_missing_file_segment_returns_404_not_found(self) -> None: """Requesting component without a file should return 404 not found.""" response = self.fetch("/_stcore/bidi-components/pkg.test_component") assert response.code == 404 assert response.body == b"not found" def test_trailing_slash_returns_404_not_found(self) -> None: """Requesting component with trailing slash should return 404 not found.""" response = self.fetch("/_stcore/bidi-components/pkg.test_component/") assert response.code == 404 assert response.body == b"not found" def test_directory_path_returns_404_not_found(self) -> None: """Requesting a directory within component should return 404 not found.""" response = self.fetch("/_stcore/bidi-components/pkg.test_component/subdir/") assert response.code == 404 assert response.body == b"not found" def test_cors_all_origins_star(self) -> None: """When CORS allows all, Access-Control-Allow-Origin should be '*'.""" with mock.patch( "streamlit.web.server.routes.allow_all_cross_origin_requests", mock.MagicMock(return_value=True), ): response = self.fetch( "/_stcore/bidi-components/pkg.test_component/index.js" ) assert response.code == 200 assert response.headers["Access-Control-Allow-Origin"] == "*" @mock.patch( "streamlit.web.server.routes.allow_all_cross_origin_requests", mock.MagicMock(return_value=False), ) @patch_config_options({"server.corsAllowedOrigins": ["http://example.com"]}) def test_cors_allowlisted_origin_echo(self) -> None: """When origin is allowlisted, it should be echoed in the header.""" response = self.fetch( "/_stcore/bidi-components/pkg.test_component/index.js", headers={"Origin": "http://example.com"}, ) assert response.code == 200 assert response.headers["Access-Control-Allow-Origin"] == "http://example.com" class BidiComponentRequestHandlerAssetDirTest(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: # type: ignore[override] self.manager = BidiComponentManager() self.temp_dir = tempfile.TemporaryDirectory() super().setUp() # Prepare a package with asset_dir and a file to be served self.package_root = Path(self.temp_dir.name) / "pkg" self.package_root.mkdir(parents=True, exist_ok=True) self.assets_dir = self.package_root / "assets" self.assets_dir.mkdir(parents=True, exist_ok=True) self.js_file_path = self.assets_dir / "bundle.js" with open(self.js_file_path, "w", encoding="utf-8") as f: f.write("console.log('served from asset_dir');") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) self.manager.register_from_manifest(manifest, self.package_root) def tearDown(self) -> None: # type: ignore[override] super().tearDown() self.temp_dir.cleanup() def get_app(self) -> tornado.web.Application: # type: ignore[override] return tornado.web.Application( [ ( r"/_stcore/bidi-components/(.*)", BidiComponentRequestHandler, {"component_manager": self.manager}, ) ] ) def test_serves_within_asset_dir(self) -> None: """Handler should serve files under manifest-declared asset_dir.""" resp = self.fetch("/_stcore/bidi-components/pkg.slider/bundle.js") assert resp.code == 200 assert resp.body.decode() == "console.log('served from asset_dir');" def test_forbids_traversal_outside_asset_dir(self) -> None: """Traversal outside asset_dir is forbidden and returns 400.""" resp = self.fetch("/_stcore/bidi-components/pkg.slider/../../etc/passwd") assert resp.code == 400 def test_absolute_path_injection_forbidden(self) -> None: """Absolute path injection via double-slash should be forbidden (400).""" # When the requested filename begins with a slash due to a double-slash in the URL, # joining with the component root would otherwise discard the root. We must reject it. resp = self.fetch("/_stcore/bidi-components/pkg.slider//etc/passwd") assert resp.code == 400 def test_symlink_escape_outside_asset_dir_forbidden(self) -> None: """Symlink in asset_dir pointing outside should be forbidden (400).""" # Create a real file outside of the component asset_dir outside_file = Path(self.temp_dir.name) / "outside.js" outside_file.write_text("console.log('outside');") # Create a symlink inside the asset_dir pointing to the outside file link_path = self.assets_dir / "link_out.js" try: # On Windows, creating symlinks may require elevated permissions; skip if unsupported os.symlink(outside_file, link_path) except (OSError, NotImplementedError): self.skipTest("Symlinks not supported in this environment") # Attempt to fetch the symlinked file via the handler resp = self.fetch("/_stcore/bidi-components/pkg.slider/link_out.js") assert resp.code == 400
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/web/server/bidi_component_request_handler_test.py", "license": "Apache License 2.0", "lines": 203, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/web/server/component_file_utils_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os from pathlib import Path from typing import TYPE_CHECKING from unittest import mock from urllib.parse import unquote import pytest from streamlit.web.server.component_file_utils import ( build_safe_abspath, guess_content_type, ) if TYPE_CHECKING: from collections.abc import Callable @pytest.fixture def root(tmp_path: Path) -> Path: """Create an isolated component root with a single file inside.""" root_dir = tmp_path / "root" root_dir.mkdir(parents=True, exist_ok=True) (root_dir / "inside.txt").write_text("ok") return root_dir @pytest.mark.parametrize( ("candidate", "expect_allowed"), [ pytest.param("inside.txt", True, id="inside_ok"), pytest.param("../etc/passwd", False, id="relative_traversal_forbidden"), pytest.param( os.sep + "etc" + os.sep + "passwd", False, id="absolute_injection_forbidden" ), ], ) def test_path_security_cases(root: Path, candidate: str, expect_allowed: bool) -> None: """Validate safe path resolution and forbidden cases (relative and absolute traversal). Parameters ---------- root Temporary component root directory fixture. candidate Relative URL path candidate to resolve under the component root. expect_allowed Whether the candidate is expected to resolve inside the root. """ abspath = build_safe_abspath(str(root), candidate) if expect_allowed: assert abspath is not None assert Path(abspath).read_text(encoding="utf-8") == "ok" else: assert abspath is None def test_rejects_symlink_escape(root: Path, tmp_path: Path) -> None: """Rejects a symlink inside root that points outside root.""" outside = tmp_path / "outside.txt" outside.write_text("nope") link_inside = root / "link.txt" try: os.symlink(outside, link_inside) except (OSError, NotImplementedError): pytest.skip("Symlinks not supported in this environment") abspath = build_safe_abspath(str(root), "link.txt") assert abspath is None def test_commonpath_valueerror_treated_as_forbidden(root: Path) -> None: """When os.path.commonpath raises ValueError (e.g., cross-drive), treat as forbidden.""" with mock.patch( "streamlit.web.server.component_file_utils.os.path.commonpath" ) as m: m.side_effect = ValueError("different drives") abspath = build_safe_abspath(str(root), "inside.txt") assert abspath is None def test_symlink_within_root_allowed(root: Path) -> None: """Allows a symlink that targets a file within the same root directory. This ensures we don't over-block legitimate symlinked resources that resolve inside the component root after ``realpath`` resolution. """ target = root / "inside.txt" link_inside = root / "alias.txt" try: os.symlink(target, link_inside) except (OSError, NotImplementedError): pytest.skip("Symlinks not supported in this environment") abspath = build_safe_abspath(str(root), "alias.txt") assert abspath is not None assert Path(abspath).read_text(encoding="utf-8") == "ok" @pytest.mark.parametrize( ("candidate", "expect"), [ pytest.param( "", lambda root: os.path.realpath(str(root)), id="empty_means_root" ), pytest.param( ".", lambda root: os.path.realpath(str(root)), id="dot_means_root" ), pytest.param( os.path.join("does", "not", "exist.txt"), lambda root: os.path.realpath(str(root / "does" / "not" / "exist.txt")), id="nonexistent_inside_root", ), ], ) def test_normalization_and_nonexistent_paths( root: Path, candidate: str, expect: Callable[[Path], str] ) -> None: """Normalizes candidates and allows non-existent paths that remain inside root. The helper under test does not enforce existence; it only enforces that the resolved path stays within the component root. """ abspath = build_safe_abspath(str(root), candidate) assert abspath is not None assert abspath == expect(root) def test_normalized_parent_segments_rejected(root: Path) -> None: """Paths containing '..' are now rejected early for SSRF protection. This is a security-motivated behavior change: paths like 'sub/../inside.txt' are rejected at validation time even if they would resolve safely. This prevents potential SSRF attacks where path traversal could be combined with other techniques. """ traversal_path = os.path.join("sub", "..", "inside.txt") assert build_safe_abspath(str(root), traversal_path) is None def test_component_root_is_symlink(tmp_path: Path) -> None: """Supports a component root that itself is a symlink to a real directory.""" real_root = tmp_path / "real_root" real_root.mkdir(parents=True, exist_ok=True) (real_root / "inside.txt").write_text("ok") link_root = tmp_path / "root_link" try: os.symlink(real_root, link_root) except (OSError, NotImplementedError): pytest.skip("Symlinks not supported in this environment") abspath = build_safe_abspath(str(link_root), "inside.txt") assert abspath == os.path.realpath(str(real_root / "inside.txt")) @pytest.mark.parametrize( ("path", "expected"), [ pytest.param("file.js.gz", "application/gzip", id="gzip_encoding_overrides"), pytest.param("file.svgz", "application/gzip", id="svgz_is_gzip"), ], ) def test_guess_content_type_gzip(path: str, expected: str) -> None: """Returns application/gzip when encoding is gzip, regardless of base type.""" assert guess_content_type(path) == expected def test_guess_content_type_other_encoding_bzip2() -> None: """Falls back to octet-stream when an encoding other than gzip is detected.""" # .bz2 is commonly recognized with encoding "bzip2" across platforms assert guess_content_type("archive.tar.bz2") == "application/octet-stream" @pytest.mark.parametrize( ("path", "expected_prefix"), [ pytest.param("note.txt", "text/plain", id="plain_text"), pytest.param("image.png", "image/png", id="png_image"), pytest.param("script.js", "application/javascript", id="javascript"), ], ) def test_guess_content_type_basic_types(path: str, expected_prefix: str) -> None: """Returns the detected mime type when there is no content encoding. We accept that the exact string can vary slightly across Python versions or platforms (e.g., application/javascript vs text/javascript), so for types known to be stable we check equality, and for JavaScript we assert a prefix. """ mime = guess_content_type(path) if path.endswith(".js"): assert ( mime.endswith("javascript") and mime.startswith("application") ) or mime.startswith("text") else: assert mime == expected_prefix def test_guess_content_type_unknown_extension() -> None: """Returns octet-stream for unknown or unregistered file extensions.""" assert ( guess_content_type("file.somethingreallyrandomext") == "application/octet-stream" ) # --------------------------------------------------------------------------- # UNC path and SSRF prevention tests # --------------------------------------------------------------------------- @pytest.mark.parametrize( "unsafe_path", [ pytest.param("\\\\server\\share\\file.js", id="unc_backslash"), pytest.param("//server/share/file.js", id="unc_forward_slash"), pytest.param("\\rooted\\path", id="rooted_backslash"), pytest.param("/etc/passwd", id="rooted_forward_slash"), pytest.param("../../../etc/passwd", id="traversal_relative"), pytest.param("foo/../../../etc/passwd", id="traversal_in_middle"), ], ) def test_rejects_unsafe_paths_before_realpath(root: Path, unsafe_path: str) -> None: """Unsafe paths must be rejected before os.path.realpath() is called. This prevents Windows UNC paths from triggering SMB connections (SSRF). """ abspath = build_safe_abspath(str(root), unsafe_path) assert abspath is None @pytest.mark.parametrize( "unsafe_path", [ pytest.param("\\\\server\\share\\file.js", id="unc_backslash"), pytest.param("//server/share/file.js", id="unc_forward_slash"), pytest.param("../../../etc/passwd", id="traversal"), ], ) def test_realpath_not_called_for_unsafe_paths(root: Path, unsafe_path: str) -> None: """Verify os.path.realpath is NOT called when an unsafe path is provided. This is a regression test for the SSRF fix. The security invariant is that realpath() must never be called on untrusted input, because on Windows it can trigger SMB connections to attacker-controlled servers. If someone refactors and moves the is_unsafe_path_pattern() check after the realpath() call, this test will catch it. """ with mock.patch( "streamlit.web.server.component_file_utils.os.path.realpath" ) as mock_realpath: result = build_safe_abspath(str(root), unsafe_path) # Should return None (rejected) assert result is None # realpath should NOT have been called at all mock_realpath.assert_not_called() @pytest.mark.parametrize( "unsafe_path", [ pytest.param("C:\\Windows\\system32\\file.dll", id="windows_drive_backslash"), pytest.param("C:/Windows/system32/file.dll", id="windows_drive_forward"), pytest.param("Z:mapped_drive_file", id="windows_drive_relative"), ], ) def test_rejects_windows_drive_paths(root: Path, unsafe_path: str) -> None: """Windows drive paths are rejected to prevent mapped drive access. This includes drive-relative paths like 'Z:foo' which on Windows resolve against the current directory of that drive. Checked on all platforms for defense-in-depth and testability (CI runs on Linux). """ abspath = build_safe_abspath(str(root), unsafe_path) assert abspath is None def test_safe_path_still_resolves_correctly(root: Path) -> None: """Ensures that safe paths still work after the security check is added. This is an anti-regression test to verify the fix doesn't break normal usage. """ abspath = build_safe_abspath(str(root), "inside.txt") assert abspath is not None assert Path(abspath).read_text(encoding="utf-8") == "ok" def test_safe_nested_path_resolves(root: Path) -> None: """Nested subdirectory paths should still resolve correctly.""" subdir = root / "sub" / "nested" subdir.mkdir(parents=True, exist_ok=True) (subdir / "deep.txt").write_text("deep content") abspath = build_safe_abspath(str(root), "sub/nested/deep.txt") assert abspath is not None assert Path(abspath).read_text(encoding="utf-8") == "deep content" @pytest.mark.parametrize( "decoded_path", [ pytest.param("../../etc/passwd", id="url_decoded_traversal"), pytest.param("\\\\server\\share", id="url_decoded_unc_backslash"), pytest.param("//server/share", id="url_decoded_unc_forward"), ], ) def test_url_decoded_paths_are_rejected(root: Path, decoded_path: str) -> None: """Verify that URL-decoded malicious paths are correctly rejected. Tornado and Starlette automatically URL-decode path parameters before passing them to handlers. This test documents that our validation works correctly on the decoded paths (e.g., %2e%2e becomes .., %5c%5c becomes \\\\). Note: Double URL encoding (e.g., %252e%252e) is not a concern because web frameworks only decode once. So %252e%252e becomes %2e%2e (literal string), not "..", which our check would not flag as traversal. This is safe because the filesystem would look for a literal "%2e%2e" directory. """ # These are example encoded forms that would decode to the test paths encoded_examples = { "../../etc/passwd": "%2e%2e/%2e%2e/etc/passwd", "\\\\server\\share": "%5c%5cserver%5cshare", "//server/share": "%2f%2fserver%2fshare", } # Verify the encoding/decoding relationship for documentation if decoded_path in encoded_examples: assert unquote(encoded_examples[decoded_path]) == decoded_path # The actual test: decoded paths should be rejected abspath = build_safe_abspath(str(root), decoded_path) assert abspath is None @pytest.mark.parametrize( "path_with_null", [ pytest.param("\x00", id="null_only"), pytest.param("file\x00.txt", id="null_in_middle"), pytest.param("\x00../secret", id="null_before_traversal"), pytest.param("safe.txt\x00", id="null_at_end"), ], ) def test_rejects_null_bytes(root: Path, path_with_null: str) -> None: """Paths containing null bytes should be rejected. Null byte injection can be used to truncate paths in some contexts. While Python 3 generally handles this safely, we reject them as defense in depth. """ assert build_safe_abspath(str(root), path_with_null) is None @pytest.mark.parametrize( "windows_special_path", [ pytest.param("\\\\?\\C:\\Windows", id="extended_length_path"), pytest.param("\\\\.\\device", id="device_namespace"), pytest.param("\\\\?\\UNC\\server\\share", id="extended_unc"), ], ) def test_rejects_windows_special_path_prefixes( root: Path, windows_special_path: str ) -> None: """Windows extended-length and device namespace paths should be rejected. These paths start with \\\\ so they're caught by the UNC check, but this test documents that coverage explicitly. """ assert build_safe_abspath(str(root), windows_special_path) is None def test_mixed_separators_not_rejected_early(root: Path) -> None: """Paths with mixed separators should not be rejected by the early validation. On Windows, backslashes are path separators. On Unix, they're valid filename characters. Safe relative paths with backslashes should not be rejected. """ # On Unix, this would look for a directory literally named "sub\nested" # On Windows, this would be equivalent to "sub/nested/file.js" # Either way, build_safe_abspath should not reject it as unsafe abspath = build_safe_abspath(str(root), "sub\\nested/file.js") # The path passes validation (not None) - it just might not exist assert abspath is not None def test_traversal_with_mixed_separators_rejected(root: Path) -> None: """Path traversal using mixed separators should be rejected.""" # These all contain '..' and should be rejected regardless of separator style mixed_traversal_paths = [ "sub\\..\\..\\secret", "sub/../..\\secret", "sub\\../secret", ] for path in mixed_traversal_paths: abspath = build_safe_abspath(str(root), path) assert abspath is None, f"Expected {path!r} to be rejected"
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/web/server/component_file_utils_test.py", "license": "Apache License 2.0", "lines": 339, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/components/v2/component_definition_resolver.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shared resolver for building component definitions with path validation. This module centralizes the logic for interpreting js/css inputs as inline content vs path/glob strings, validating them against a component's asset directory, and producing a BidiComponentDefinition with correct asset-relative URLs used by the server. """ from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING from streamlit.components.v2.component_path_utils import ComponentPathUtils from streamlit.components.v2.component_registry import BidiComponentDefinition from streamlit.errors import StreamlitAPIException if TYPE_CHECKING: from streamlit.components.v2.component_manager import BidiComponentManager def build_definition_with_validation( *, manager: BidiComponentManager, component_key: str, html: str | None, css: str | None, js: str | None, ) -> BidiComponentDefinition: """Construct a definition and validate ``js``/``css`` inputs against ``asset_dir``. Parameters ---------- manager : BidiComponentManager Component manager used to resolve the component's ``asset_dir`` and related metadata. component_key : str Fully-qualified name of the component to build a definition for. html : str | None Inline HTML content to include in the definition. If ``None``, the component will not include HTML content. css : str | None Either inline CSS content or a path/glob to a CSS file inside the component's ``asset_dir``. Inline strings are kept as-is; file-backed inputs are validated and converted to an ``asset_dir``-relative URL. js : str | None Either inline JavaScript content or a path/glob to a JS file inside the component's ``asset_dir``. Inline strings are kept as-is; file-backed inputs are validated and converted to an ``asset_dir``-relative URL. Returns ------- BidiComponentDefinition A component definition with inline content preserved and file-backed entries resolved to absolute filesystem paths plus their ``asset_dir``-relative URLs. Raises ------ StreamlitAPIException If a path/glob is provided but the component has no declared ``asset_dir``, if a glob resolves to zero or multiple files, or if any resolved path escapes the declared ``asset_dir``. Notes ----- - Inline strings are treated as content (no manifest required). - Path-like strings require the component to be declared in the package manifest with an ``asset_dir``. - Globs are supported only within ``asset_dir`` and must resolve to exactly one file. - Relative paths are resolved strictly against the component's ``asset_dir`` and must remain within it after resolution. Absolute paths are not allowed. - For file-backed entries, the URL sent to the frontend is the ``asset_dir``-relative path, served under ``/_stcore/bidi-components/<component>/<relative_path>``. """ asset_root = manager.get_component_asset_root(component_key) def _resolve_entry( value: str | None, *, kind: str ) -> tuple[str | None, str | None]: # Inline content: None rel URL if value is None: return None, None if ComponentPathUtils.looks_like_inline_content(value): return value, None # For path-like strings, asset_root must exist if asset_root is None: raise StreamlitAPIException( f"Component '{component_key}' must be declared in pyproject.toml with asset_dir " f"to use file-backed {kind}." ) value_str = value # If looks like a glob, resolve strictly inside asset_root if ComponentPathUtils.has_glob_characters(value_str): resolved = ComponentPathUtils.resolve_glob_pattern(value_str, asset_root) ComponentPathUtils.ensure_within_root(resolved, asset_root, kind=kind) # Use resolved absolute paths to avoid macOS /private prefix mismatch rel_url = str( resolved.resolve().relative_to(asset_root.resolve()).as_posix() ) return str(resolved), rel_url # Concrete path: must be asset-dir-relative (reject absolute & traversal) ComponentPathUtils.validate_path_security(value_str) candidate = asset_root / Path(value_str) ComponentPathUtils.ensure_within_root(candidate, asset_root, kind=kind) resolved_candidate = candidate.resolve() rel_url = str(resolved_candidate.relative_to(asset_root.resolve()).as_posix()) return str(resolved_candidate), rel_url css_value, css_rel = _resolve_entry(css, kind="css") js_value, js_rel = _resolve_entry(js, kind="js") # Build definition with possible asset_dir-relative paths return BidiComponentDefinition( name=component_key, html=html, css=css_value, js=js_value, css_asset_relative_path=css_rel, js_asset_relative_path=js_rel, )
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/component_definition_resolver.py", "license": "Apache License 2.0", "lines": 123, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/component_manager.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Custom Components v2 manager and supporting orchestration. This module composes the registry, manifest handling, and file watching capabilities for Streamlit's Custom Components v2. It provides a unified interface to register components from manifests or individual definitions, query component metadata and asset paths, and react to on-disk changes by re-resolving component definitions. """ from __future__ import annotations import threading from dataclasses import dataclass from typing import TYPE_CHECKING, Final from streamlit.components.v2.component_definition_resolver import ( build_definition_with_validation, ) from streamlit.components.v2.component_file_watcher import ComponentFileWatcher from streamlit.components.v2.component_manifest_handler import ComponentManifestHandler from streamlit.components.v2.component_registry import ( BidiComponentDefinition, BidiComponentRegistry, ) from streamlit.logger import get_logger if TYPE_CHECKING: from pathlib import Path from streamlit.components.v2.manifest_scanner import ComponentManifest _LOGGER: Final = get_logger(__name__) @dataclass class _ApiInputs: """Inputs provided via the Python API to resolve a component definition. Attributes ---------- css : str | None Inline CSS content or a path/glob to a CSS asset within ``asset_dir``. js : str | None Inline JS content or a path/glob to a JS asset within ``asset_dir``. """ css: str | None js: str | None class BidiComponentManager: """Manager class that composes component registry, manifest handler, and file watcher. This class provides a unified interface for working with bidirectional components while maintaining clean separation of concerns through composition. It handles the coordination and lifecycle management of all component-related functionality. Component Lifecycle ------------------- The lifecycle of a component managed by this class involves four key stages: 1. **Discovery**: On startup, ``discover_and_register_components`` scans for installed packages with component manifests (``pyproject.toml``). For each component found, a placeholder definition containing only its name and ``asset_dir`` is registered. This makes the system aware of all available installed components from the outset. 2. **Definition & Validation**: When a user's script calls the public API (e.g., ``st.components.v2.component(...)``), the manager invokes ``build_definition_with_validation``. This function is the single, centralized point for all validation. It resolves file paths, performs security checks against the component's ``asset_dir``, and produces a complete, validated ``BidiComponentDefinition``. 3. **Registration**: The validated definition is then passed to the registry's ``register`` method. This adds the complete definition, overwriting the placeholder if one existed from the discovery phase. 4. **Updating**: The ``ComponentFileWatcher`` monitors the ``asset_dir`` for changes. On a change, it triggers a re-computation of the definition using the original API inputs, runs it through the same validation logic, and updates the registry with the new definition via the stricter ``update_component`` method. Notes ----- This manager intentionally favors composition over inheritance and delegates specialized responsibilities to ``BidiComponentRegistry``, ``ComponentManifestHandler``, and ``ComponentFileWatcher``. """ def __init__( self, registry: BidiComponentRegistry | None = None, manifest_handler: ComponentManifestHandler | None = None, file_watcher: ComponentFileWatcher | None = None, ) -> None: """Initialize the component manager. Parameters ---------- registry : BidiComponentRegistry, optional Component registry instance. If not provided, a new one will be created. manifest_handler : ComponentManifestHandler, optional Manifest handler instance. If not provided, a new one will be created. file_watcher : ComponentFileWatcher, optional File watcher instance. If not provided, a new one will be created. """ # Create dependencies self._registry = registry or BidiComponentRegistry() self._manifest_handler = manifest_handler or ComponentManifestHandler() # Store API inputs for re-resolution on change events self._api_inputs: dict[str, _ApiInputs] = {} self._api_inputs_lock = threading.Lock() self._file_watcher = file_watcher or ComponentFileWatcher( self._on_components_changed ) def record_api_inputs( self, component_key: str, css: str | None, js: str | None ) -> None: """Record original API inputs for later re-resolution on file changes. Parameters ---------- component_key : str Fully-qualified component name. css : str | None Inline CSS or a path/glob to a CSS file within the component's ``asset_dir``. js : str | None Inline JavaScript or a path/glob to a JS file within the component's ``asset_dir``. """ with self._api_inputs_lock: self._api_inputs[component_key] = _ApiInputs(css=css, js=js) def register_from_manifest( self, manifest: ComponentManifest, package_root: Path ) -> None: """Register components from a manifest file. This is a high-level method that processes the manifest and registers all components found within it. Parameters ---------- manifest : ComponentManifest The component manifest to process. package_root : Path Root path of the package containing the components. """ # First process the manifest component_definitions = self._manifest_handler.process_manifest( manifest, package_root ) # Register all component definitions self._registry.register_components_from_definitions(component_definitions) _LOGGER.debug( "Registered %d components from manifest", len(component_definitions) ) def register(self, definition: BidiComponentDefinition) -> None: """Register a single component definition. Parameters ---------- definition : BidiComponentDefinition The component definition to register. """ self._registry.register(definition) def get(self, name: str) -> BidiComponentDefinition | None: """Get a component definition by name. Parameters ---------- name : str The name of the component to retrieve. Returns ------- BidiComponentDefinition or None The component definition if found; otherwise ``None``. """ return self._registry.get(name) def build_definition_with_validation( self, *, component_key: str, html: str | None, css: str | None, js: str | None, ) -> BidiComponentDefinition: """Build a validated component definition for the given inputs. Parameters ---------- component_key : str Fully-qualified component name the definition is for. html : str | None Inline HTML content to include in the definition. css : str | None Inline CSS content or a path/glob under the component's asset_dir. js : str | None Inline JS content or a path/glob under the component's asset_dir. Returns ------- BidiComponentDefinition The fully validated component definition. """ return build_definition_with_validation( manager=self, component_key=component_key, html=html, css=css, js=js, ) def get_component_asset_root(self, name: str) -> Path | None: """Get the asset root for a manifest-backed component. Parameters ---------- name : str The name of the component to get the asset root for. Returns ------- Path or None The component's ``asset_root`` directory if found; otherwise ``None``. """ return self._manifest_handler.get_asset_root(name) def unregister(self, name: str) -> None: """Unregister a component by name. Parameters ---------- name : str The name of the component to unregister. """ self._registry.unregister(name) def clear(self) -> None: """Clear all registered components.""" self._registry.clear() def get_component_path(self, name: str) -> str | None: """Get the filesystem path for a manifest-backed component. Parameters ---------- name : str The name of the component. Returns ------- str or None The component's ``asset_dir`` directory if found; otherwise ``None``. """ asset_root = self._manifest_handler.get_asset_root(name) if asset_root is not None: return str(asset_root) return None def start_file_watching(self) -> None: """Start file watching for component changes.""" if self._file_watcher.is_watching_active: _LOGGER.warning("File watching is already started") return # Get asset watch roots from manifest handler asset_roots = self._manifest_handler.get_asset_watch_roots() # Start file watching self._file_watcher.start_file_watching(asset_roots) if self._file_watcher.is_watching_active: _LOGGER.debug("Started file watching for component changes") # type: ignore[unreachable] else: _LOGGER.debug("File watching not started") def discover_and_register_components( self, *, start_file_watching: bool = True ) -> None: """Discover installed v2 components and register them. This scans installed distributions for manifests, registers all discovered components, and starts file watching for development workflows. Parameters ---------- start_file_watching : bool Whether to start file watching after components are registered. """ try: from streamlit.components.v2.manifest_scanner import ( scan_component_manifests, ) manifests = scan_component_manifests() for manifest, package_root in manifests: self.register_from_manifest(manifest, package_root) _LOGGER.debug( "Registered components from pyproject.toml: %s v%s", manifest.name, manifest.version, ) # Start file watching for development mode after all components are registered if start_file_watching: self.start_file_watching() except Exception as e: _LOGGER.warning("Failed to scan component manifests: %s", e) def stop_file_watching(self) -> None: """Stop file watching.""" if not self._file_watcher.is_watching_active: _LOGGER.warning("File watching is not started") return self._file_watcher.stop_file_watching() _LOGGER.debug("Stopped file watching") def get_metadata(self, component_name: str) -> ComponentManifest | None: """Get metadata for a component. Parameters ---------- component_name : str The name of the component to get metadata for. Returns ------- ComponentManifest or None The component metadata if found; otherwise ``None``. """ return self._manifest_handler.get_metadata(component_name) def _on_components_changed(self, component_names: list[str]) -> None: """Handle change events for components' asset roots. For each component, re-resolve from stored API inputs and update the registry with the new definition if resolution succeeds. Parameters ---------- component_names : list[str] Fully-qualified component names whose watched files changed. """ for name in component_names: try: updated_def = self._recompute_definition_from_api(name) if updated_def is not None: self._registry.update_component(updated_def) except Exception: # noqa: PERF203 _LOGGER.exception("Failed to update component after change: %s", name) def _recompute_definition_from_api( self, component_name: str ) -> BidiComponentDefinition | None: """Recompute a component's definition using previously recorded API inputs. Parameters ---------- component_name : str Fully-qualified component name to recompute. Returns ------- BidiComponentDefinition | None A fully validated component definition suitable for replacing the stored entry in the registry, or ``None`` if recomputation failed or no API inputs were previously recorded. """ with self._api_inputs_lock: inputs = self._api_inputs.get(component_name) if inputs is None: return None # Get existing def to preserve html unless new content is provided later existing_def = self._registry.get(component_name) html_value = existing_def.html if existing_def else None try: # Resolve a fully validated definition from stored API inputs and # the preserved html value from the existing definition. new_def = self.build_definition_with_validation( component_key=component_name, html=html_value, css=inputs.css, js=inputs.js, ) except Exception as e: _LOGGER.debug( "Skipping update for %s due to re-resolution error: %s", component_name, e, ) return None return new_def @property def is_file_watching_started(self) -> bool: """Check if file watching is currently active. Returns ------- bool True if file watching is started, False otherwise """ return self._file_watcher.is_watching_active
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/component_manager.py", "license": "Apache License 2.0", "lines": 364, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/get_bidi_component_manager.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Accessors for the BidiComponentManager used by Custom Components v2. This module exposes `get_bidi_component_manager`, which returns the singleton `BidiComponentManager` registered on the active Streamlit runtime. When no runtime is active, a local manager instance is created and returned. """ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from streamlit.components.v2.component_manager import BidiComponentManager def get_bidi_component_manager() -> BidiComponentManager: """Return the singleton ``BidiComponentManager`` instance. Returns ------- BidiComponentManager The singleton BidiComponentManager instance. Notes ----- If the Streamlit runtime is not running, a local ``BidiComponentManager`` is created and returned. """ from streamlit.components.v2.component_manager import BidiComponentManager from streamlit.runtime import Runtime if Runtime.exists(): return Runtime.instance().bidi_component_registry # Return a local manager when running without the streamlit runtime return BidiComponentManager()
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/get_bidi_component_manager.py", "license": "Apache License 2.0", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_manager.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import tempfile import threading import time from pathlib import Path from typing import TYPE_CHECKING from streamlit.components.v2 import component as component_api from streamlit.components.v2.component_manager import BidiComponentManager from streamlit.components.v2.component_registry import BidiComponentDefinition from streamlit.components.v2.manifest_scanner import ComponentConfig, ComponentManifest if TYPE_CHECKING: import pytest def _setup_manager_with_manifest(tmp_path: Path) -> tuple[BidiComponentManager, str]: """Set up a BidiComponentManager with a manifest-backed component. Parameters ---------- tmp_path : Path A temporary path to create the component package and assets. Returns ------- tuple[BidiComponentManager, str] A tuple containing the component manager and the component name. """ manager = BidiComponentManager() package_root = tmp_path / "pkg" assets = package_root / "assets" (assets / "js").mkdir(parents=True) (assets / "js" / "main.js").write_text("console.log('ok');") (assets / "style.css").write_text(".x{color:red}") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="comp", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) comp_name = "pkg.comp" manager.register(BidiComponentDefinition(name=comp_name, html="<div>ok</div>")) return manager, comp_name def test_manager_uses_lock_for_api_inputs(tmp_path: Path) -> None: """Verify manager exposes a lock and handles inputs safely during updates.""" manager, comp_name = _setup_manager_with_manifest(tmp_path) # The manager is expected to expose an _api_inputs_lock used to guard access. assert hasattr(manager, "_api_inputs_lock"), ( "BidiComponentManager must define _api_inputs_lock to guard _api_inputs" ) # Exercise calls to ensure no exceptions and that state updates correctly manager.record_api_inputs(comp_name, css="*.css", js="js/*.js") manager._on_components_changed([comp_name]) d = manager.get(comp_name) assert d is not None assert d.html_content == "<div>ok</div>" def test_concurrent_record_and_change_no_exceptions(tmp_path: Path) -> None: """Stress concurrent access to record_api_inputs and change handling. This validates that under concurrent use there are no exceptions and the registry remains consistent. This will still pass without a lock in CPython in many cases due to the GIL, but combined with the lock assertion test above, we get stronger guarantees. """ manager, comp_name = _setup_manager_with_manifest(tmp_path) stop_event = threading.Event() errors: list[Exception] = [] def writer() -> None: try: while not stop_event.is_set(): manager.record_api_inputs(comp_name, css="*.css", js="js/*.js") except Exception as e: # pragma: no cover - diagnostic capture errors.append(e) def reader() -> None: try: while not stop_event.is_set(): manager._on_components_changed([comp_name]) except Exception as e: # pragma: no cover - diagnostic capture errors.append(e) threads = [threading.Thread(target=writer), threading.Thread(target=reader)] for t in threads: t.start() time.sleep(0.2) stop_event.set() for t in threads: t.join(timeout=2) assert not errors, f"Unexpected errors under concurrency: {errors}" # Registry remains valid d = manager.get(comp_name) assert d is not None assert d.html_content == "<div>ok</div>" def test_get_component_path_prefers_asset_dir_when_present() -> None: """Verify manager returns manifest asset_dir over registry paths.""" manager = BidiComponentManager() with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) # Create a registry-backed JS file in dir A dir_a = tmp_path / "dir_a" dir_a.mkdir(parents=True) js_a = dir_a / "index.js" js_a.write_text("console.log('A');") # Register component with file-backed JS path (registry fallback) comp_name = "pkg.slider" manager.register( BidiComponentDefinition( name=comp_name, js=str(js_a), ) ) # Prepare manifest-declared asset_dir (dir B) package_root = tmp_path / "package" assets_b = package_root / "assets" assets_b.mkdir(parents=True) (assets_b / "index.js").write_text("console.log('B');") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) # Register manifest; manager should now prefer asset_dir manager.register_from_manifest(manifest, package_root) got = manager.get_component_path(comp_name) assert got is not None assert os.path.realpath(got) == os.path.realpath(str(assets_b)) def test_register_from_manifest_does_not_require_asset_dir() -> None: """Verify registering a component without asset_dir works.""" manager = BidiComponentManager() with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) package_root = tmp_path / "package" package_root.mkdir(parents=True) manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="no_assets")], ) manager.register_from_manifest(manifest, package_root) asset_root = manager.get_component_path("pkg.no_assets") assert asset_root is None def test_on_components_changed_preserves_html_and_resolves_assets( tmp_path: Path, ) -> None: """Verify recompute preserves html and resolves assets under asset_dir.""" manager = BidiComponentManager() # Prepare manifest with asset_dir package_root = tmp_path / "package" assets = package_root / "assets" (assets / "js").mkdir(parents=True) (assets / "style.css").write_text(".x { color: red; }") (assets / "js" / "main.js").write_text("console.log('ok');") manifest = ComponentManifest( name="pkg", version="0.0.1", components=[ComponentConfig(name="slider", asset_dir="assets")], ) manager.register_from_manifest(manifest, package_root) comp_name = "pkg.slider" # Existing definition with html to be preserved during recompute manager.register(BidiComponentDefinition(name=comp_name, html="<p>orig</p>")) # Record API inputs as globs resolved relative to asset_dir manager.record_api_inputs(comp_name, css="*.css", js="js/*.js") # Trigger change handler for this component manager._on_components_changed([comp_name]) # Validate outcome in the registry d = manager.get(comp_name) assert d is not None assert d.html_content == "<p>orig</p>" # File-backed entries expose asset-dir-relative URLs assert d.css_url == "style.css" assert d.js_url == "js/main.js" # Content properties must be None for file-backed entries assert d.css_content is None assert d.js_content is None def _make_manifest(pkg_name: str, comp_name: str, asset_dir: str) -> ComponentManifest: """Create a ComponentManifest for testing.""" return ComponentManifest( name=pkg_name, version="0.0.1", components=[ComponentConfig(name=comp_name, asset_dir=asset_dir)], ) def _write(path: Path, content: str) -> None: """Write content to a file, creating parent directories if needed.""" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content, encoding="utf-8") def test_re_resolves_js_glob_on_change(monkeypatch: pytest.MonkeyPatch) -> None: """Verify that JS glob paths are re-resolved on component changes.""" with tempfile.TemporaryDirectory() as td: root = Path(td) assets = root / "assets" js_dir = assets / "js" # Initial file first_js = js_dir / "index-abc123.js" _write(first_js, "console.log('abc');") # Register manifest with asset_dir manager = BidiComponentManager() manifest = _make_manifest("pkg", "comp", asset_dir="assets") manager.register_from_manifest(manifest, root) # Bind public API to our manager instance monkeypatch.setattr( "streamlit.components.v2.get_bidi_component_manager", lambda: manager, ) # Register runtime API with a JS glob under asset_dir component_api("pkg.comp", js="js/index-*.js") initial = manager.get("pkg.comp") assert initial is not None assert initial.js is not None assert initial.js.endswith("index-abc123.js") assert initial.js_url == "js/index-abc123.js" # Simulate a new build replacing the hashed file first_js.unlink() second_js = js_dir / "index-def456.js" _write(second_js, "console.log('def');") # Trigger change handling manager._on_components_changed(["pkg.comp"]) # type: ignore[attr-defined] updated = manager.get("pkg.comp") assert updated is not None assert updated.js is not None assert updated.js.endswith("index-def456.js") assert updated.js_url == "js/index-def456.js" def test_re_resolution_no_match_keeps_previous(monkeypatch: pytest.MonkeyPatch) -> None: """Verify that re-resolution with no match preserves the previous value.""" with tempfile.TemporaryDirectory() as td: root = Path(td) assets = root / "assets" js_dir = assets / "js" # Initial file first_js = js_dir / "index-abc123.js" _write(first_js, "console.log('abc');") manager = BidiComponentManager() manifest = _make_manifest("pkg2", "comp", asset_dir="assets") manager.register_from_manifest(manifest, root) monkeypatch.setattr( "streamlit.components.v2.get_bidi_component_manager", lambda: manager, ) component_api("pkg2.comp", js="js/index-*.js") baseline = manager.get("pkg2.comp") assert baseline is not None assert baseline.js is not None assert baseline.js.endswith("index-abc123.js") # Remove the only matching file -> glob would have zero matches now first_js.unlink() manager._on_components_changed(["pkg2.comp"]) # type: ignore[attr-defined] # Definition should remain unchanged after = manager.get("pkg2.comp") assert after is not None assert after.js is not None assert after.js.endswith("index-abc123.js")
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_component_manager.py", "license": "Apache License 2.0", "lines": 257, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/components/v2/component_file_watcher.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Component file watching utilities. This module provides the `ComponentFileWatcher`, a utility that watches component asset directories for changes and notifies a caller-provided callback with the affected component names. It abstracts the underlying path-watcher implementation and ensures exception-safe startup and cleanup. Why this exists --------------- Streamlit supports advanced Custom Components that ship a package of static assets (for example, a Vite/Webpack build output). While a user develops their app, those frontend files may change. The component registry for Custom Components v2 must stay synchronized with the on-disk assets so that the server can resolve the up-to-date files. This watcher exists to keep the registry in sync by listening for changes in component asset roots and notifying a higher-level manager that can re-resolve the affected component definitions. Notes ----- - Watching is directory-based with a recursive glob ("**/*"). - Common noisy directories (e.g., ``node_modules``) are ignored in callbacks. - Startup is exception-safe and does not leak partially created watchers. See Also -------- - :class:`streamlit.watcher.local_sources_watcher.LocalSourcesWatcher` - watches app source files per session to trigger reruns. - :class:`streamlit.components.v2.component_registry.BidiComponentRegistry` - the server-side store of Custom Component v2 definitions that reacts to watcher notifications. """ from __future__ import annotations import threading from typing import TYPE_CHECKING, Final, Protocol, cast from streamlit.logger import get_logger if TYPE_CHECKING: from collections.abc import Callable from pathlib import Path _LOGGER: Final = get_logger(__name__) class _HasClose(Protocol): def close(self) -> None: ... class ComponentFileWatcher: """Handle file watching for component asset directories. Parameters ---------- component_update_callback : Callable[[list[str]], None] Callback invoked when files change under any watched directory. It receives a list of component names affected by the change. """ def __init__(self, component_update_callback: Callable[[list[str]], None]) -> None: """Initialize the file watcher. Parameters ---------- component_update_callback : Callable[[list[str]], None] Callback function to call when components under watched roots change. Signature: (affected_component_names) """ self._component_update_callback = component_update_callback self._lock = threading.Lock() # File watching state self._watched_directories: dict[ str, list[str] ] = {} # directory -> component_names self._path_watchers: list[_HasClose] = [] # Store actual watcher instances self._watching_active = False # Store asset roots to watch: component_name -> asset_root self._asset_watch_roots: dict[str, Path] = {} # Default noisy directories to ignore in callbacks self._ignored_dirs: tuple[str, ...] = ( "__pycache__", ".cache", ".git", ".hg", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".svn", ".swc", ".yarn", "coverage", "node_modules", "venv", ) @property def is_watching_active(self) -> bool: """Check if file watching is currently active. Returns ------- bool True if file watching is active, False otherwise """ return self._watching_active def start_file_watching(self, asset_watch_roots: dict[str, Path]) -> None: """Start file watching for asset roots. Parameters ---------- asset_watch_roots : dict[str, Path] Mapping of component names to asset root directories to watch. Notes ----- The method is idempotent: it stops any active watchers first, then re-initializes watchers for the provided ``asset_watch_roots``. """ # Always stop first to ensure a clean state, then start with the new roots. # This sequencing avoids races between concurrent stop/start calls. self.stop_file_watching() self._start_file_watching(asset_watch_roots) def stop_file_watching(self) -> None: """Stop file watching and clean up watchers. Notes ----- This method is safe to call multiple times and will no-op if watching is not active. """ with self._lock: if not self._watching_active: return # Close all path watchers for watcher in self._path_watchers: try: watcher.close() except Exception: # noqa: PERF203 _LOGGER.exception("Failed to close path watcher") self._path_watchers.clear() self._watched_directories.clear() # Also clear asset root references to avoid stale state retention self._asset_watch_roots.clear() self._watching_active = False _LOGGER.debug("Stopped file watching for component registry") def _start_file_watching(self, asset_watch_roots: dict[str, Path]) -> None: """Internal method to start file watching with the given roots. This method is exception-safe: in case of failures while creating watchers, any previously created watcher instances are closed and no internal state is committed. """ with self._lock: if self._watching_active: return if not asset_watch_roots: _LOGGER.debug("No asset roots to watch") return try: path_watcher_class = self._get_default_path_watcher_class() if path_watcher_class is None: # NoOp watcher; skip activation return directories_to_watch = self._prepare_directories_to_watch( asset_watch_roots ) new_watchers, new_watched_dirs = self._build_watchers_for_directories( path_watcher_class, directories_to_watch ) # Commit new watchers and state only after successful creation if new_watchers: self._commit_watch_state( new_watchers, new_watched_dirs, asset_watch_roots ) else: _LOGGER.debug("No directories were watched; staying inactive") except Exception: _LOGGER.exception("Failed to start file watching") def _get_default_path_watcher_class(self) -> type | None: """Return the default path watcher class. Returns ------- type | None The concrete path watcher class to instantiate, or ``None`` if the NoOp watcher is configured and file watching should be skipped. """ from streamlit.watcher.path_watcher import ( NoOpPathWatcher, get_default_path_watcher_class, ) path_watcher_class = get_default_path_watcher_class() if path_watcher_class is NoOpPathWatcher: _LOGGER.debug("NoOpPathWatcher in use; skipping component file watching") return None return path_watcher_class def _prepare_directories_to_watch( self, asset_watch_roots: dict[str, Path] ) -> dict[str, list[str]]: """Build a mapping of directory to component names. Parameters ---------- asset_watch_roots : dict[str, Path] Mapping of component names to their asset root directories. Returns ------- dict[str, list[str]] A map from absolute directory path to a deduplicated list of component names contained in that directory. """ directories_to_watch: dict[str, list[str]] = {} for comp_name, root in asset_watch_roots.items(): directory = str(root.resolve()) if directory not in directories_to_watch: directories_to_watch[directory] = [] if comp_name not in directories_to_watch[directory]: directories_to_watch[directory].append(comp_name) return directories_to_watch def _build_watchers_for_directories( self, path_watcher_class: type, directories_to_watch: dict[str, list[str]] ) -> tuple[list[_HasClose], dict[str, list[str]]]: """Create watchers for directories with rollback on failure. Parameters ---------- path_watcher_class : type The path watcher class to instantiate for each directory. directories_to_watch : dict[str, list[str]] A map of directory to the associated component name list. Returns ------- tuple[list[_HasClose], dict[str, list[str]]] The list of created watcher instances and the watched directory mapping. Raises ------ Exception Propagates any exception during watcher creation after closing already-created watchers. """ new_watchers: list[_HasClose] = [] new_watched_dirs: dict[str, list[str]] = {} for directory, component_names in directories_to_watch.items(): try: cb = self._make_directory_callback(tuple(component_names)) # Use a glob pattern that matches all files to let Streamlit's # watcher handle MD5 calculation and change detection watcher = path_watcher_class( directory, cb, glob_pattern="**/*", allow_nonexistent=False, ) new_watchers.append(cast("_HasClose", watcher)) new_watched_dirs[directory] = component_names _LOGGER.debug( "Prepared watcher for directory %s (components: %s)", directory, component_names, ) except Exception: # noqa: PERF203 # Roll back watchers created so far self._rollback_watchers(new_watchers) raise return new_watchers, new_watched_dirs def _commit_watch_state( self, new_watchers: list[_HasClose], new_watched_dirs: dict[str, list[str]], asset_watch_roots: dict[str, Path], ) -> None: """Commit created watchers and mark watching active. Parameters ---------- new_watchers : list[_HasClose] Fully initialized watcher instances. new_watched_dirs : dict[str, list[str]] Mapping from directory to component names. asset_watch_roots : dict[str, Path] The asset roots used to initialize watchers; stored for reference. """ self._path_watchers = new_watchers self._watched_directories = new_watched_dirs self._asset_watch_roots = dict(asset_watch_roots) self._watching_active = True _LOGGER.debug( "Started file watching for %d directories", len(self._watched_directories) ) def _rollback_watchers(self, watchers: list[_HasClose]) -> None: """Close any created watchers when setup fails. Parameters ---------- watchers : list[_HasClose] Watcher instances that were successfully created before a failure. """ for w in watchers: try: w.close() except Exception: # noqa: PERF203 _LOGGER.exception("Failed to close path watcher during rollback") def _make_directory_callback(self, comps: tuple[str, ...]) -> Callable[[str], None]: """Create a callback for a directory watcher that captures component names.""" def callback(changed_path: str) -> None: if self._is_in_ignored_directory(changed_path): _LOGGER.debug("Ignoring change in noisy directory: %s", changed_path) return _LOGGER.debug( "Directory change detected: %s, checking components: %s", changed_path, comps, ) self._handle_component_change(list(comps)) return callback def _handle_component_change(self, affected_components: list[str]) -> None: """Handle component changes for both directory and file events. Parameters ---------- affected_components : list[str] List of component names affected by the change """ if not self._watching_active: return # Notify manager to handle re-resolution based on recorded API inputs try: self._component_update_callback(affected_components) except Exception: # Never allow exceptions from user callbacks to break watcher loops _LOGGER.exception("Component update callback raised") def _is_in_ignored_directory(self, changed_path: str) -> bool: """Return True if the changed path is inside an ignored directory. Parameters ---------- changed_path : str The filesystem path that triggered the change event. Returns ------- bool True if the path is located inside one of the ignored directories, False otherwise. """ try: from pathlib import Path as _Path parts = set(_Path(changed_path).resolve().parts) return any(ignored in parts for ignored in self._ignored_dirs) except Exception: return False
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/component_file_watcher.py", "license": "Apache License 2.0", "lines": 338, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_file_watcher.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import tempfile from pathlib import Path from unittest.mock import Mock, patch import pytest from streamlit.components.v2.component_file_watcher import ComponentFileWatcher @pytest.fixture def temp_component_files(): """Create temporary directory structure with component files for testing.""" temp_dir = tempfile.TemporaryDirectory() temp_path = Path(temp_dir.name) # Create directory structure js_dir = temp_path / "js" css_dir = temp_path / "css" js_dir.mkdir() css_dir.mkdir() # Create test files js_file = js_dir / "component.js" js_file.write_text("console.log('original');") css_file = css_dir / "styles.css" css_file.write_text(".test { color: red; }") # Create glob pattern files glob_js_file = js_dir / "component-v1.0.js" glob_js_file.write_text("console.log('glob v1');") glob_css_file = css_dir / "styles-v1.0.css" glob_css_file.write_text(".glob { color: blue; }") yield { "temp_dir": temp_path, "js_file": js_file, "css_file": css_file, "glob_js_file": glob_js_file, "glob_css_file": glob_css_file, } temp_dir.cleanup() @pytest.fixture def mock_callback(): """Create a mock callback function.""" return Mock() @pytest.fixture def file_watcher(mock_callback): """Create a ComponentFileWatcher instance with mock callback.""" return ComponentFileWatcher(mock_callback) def test_init(mock_callback): """Test initialization of ComponentFileWatcher.""" watcher = ComponentFileWatcher(mock_callback) assert watcher._component_update_callback is mock_callback assert not watcher.is_watching_active assert watcher._watched_directories == {} assert watcher._path_watchers == [] assert watcher._asset_watch_roots == {} def test_start_file_watching_no_watchers(file_watcher): """Test starting file watching with no asset roots.""" file_watcher.start_file_watching({}) assert not file_watcher.is_watching_active @pytest.mark.parametrize( ("roots_kind", "expected_watchers", "expected_dirs"), [ ("single", 1, 1), ("multiple", 2, 2), ("shared", 1, 1), ], ) def test_start_file_watching_various_roots( file_watcher, temp_component_files, roots_kind: str, expected_watchers: int, expected_dirs: int, ): """Start watching with different root configurations and verify watcher counts. Parameters ---------- roots_kind One of ``single``, ``multiple``, or ``shared`` to setup asset roots. expected_watchers Expected number of watcher instances created. expected_dirs Expected number of watched directories recorded. """ mock_watcher_instance = Mock() with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=Mock(return_value=mock_watcher_instance), ): if roots_kind == "single": asset_roots = {"test.component": temp_component_files["temp_dir"]} elif roots_kind == "multiple": js_root = temp_component_files["temp_dir"] / "js" css_root = temp_component_files["temp_dir"] / "css" asset_roots = { "test.js_component": js_root, "test.css_component": css_root, } else: # shared root = temp_component_files["temp_dir"] asset_roots = {"test.direct": root, "test.glob": root} file_watcher.start_file_watching(asset_roots) assert file_watcher.is_watching_active assert len(file_watcher._path_watchers) == expected_watchers assert len(file_watcher._watched_directories) == expected_dirs def test_stop_file_watching(file_watcher): """Test stopping file watching.""" # Mock some active watchers mock_watcher1 = Mock() mock_watcher2 = Mock() file_watcher._path_watchers = [mock_watcher1, mock_watcher2] file_watcher._watched_directories = {"dir1": ["comp1"]} # No file watchers in directory-only approach file_watcher._watching_active = True # Seed asset roots to verify cleanup file_watcher._asset_watch_roots = {"comp1": Path("/tmp")} file_watcher.stop_file_watching() # Should have closed all watchers mock_watcher1.close.assert_called_once() mock_watcher2.close.assert_called_once() # Should have cleared all state assert not file_watcher.is_watching_active assert file_watcher._path_watchers == [] assert file_watcher._watched_directories == {} assert file_watcher._asset_watch_roots == {} def test_handle_component_change_catches_callback_exceptions(file_watcher): """Ensure exceptions in the update callback are caught and logged.""" file_watcher._watching_active = True # Replace the callback with a raising one def raising_callback(_components): raise RuntimeError("boom") file_watcher._component_update_callback = raising_callback # Patch logger.exception to ensure we log instead of propagating with patch("streamlit.components.v2.component_file_watcher._LOGGER") as logger_mock: # Should not raise file_watcher._handle_component_change(["test.component"]) logger_mock.exception.assert_called_once() # Subsequent normal callbacks should still be invoked ok_mock = Mock() file_watcher._component_update_callback = ok_mock file_watcher._handle_component_change(["test.component"]) ok_mock.assert_called_once_with(["test.component"]) def test_stop_file_watching_with_close_errors(file_watcher): """Test stopping file watching when watcher.close() raises an exception.""" # Mock a watcher that raises an exception on close mock_watcher = Mock() mock_watcher.close.side_effect = Exception("Close failed") file_watcher._path_watchers = [mock_watcher] file_watcher._watching_active = True # Should not raise exception, just log it file_watcher.stop_file_watching() # Should still clean up state assert not file_watcher.is_watching_active assert file_watcher._path_watchers == [] def test_change_event_triggers_callback(file_watcher, temp_component_files): """Simulate a change event and ensure the update callback is invoked once.""" file_watcher._watching_active = True file_watcher._handle_component_change(["test.component"]) # simulate both kinds file_watcher._component_update_callback.assert_called_once() @pytest.mark.parametrize( "attr_name", [ "_re_resolve_component_patterns", "_resolve_single_pattern", "_extract_html_content", ], ) def test_no_legacy_helpers_present(file_watcher, attr_name: str): """Assert that removed legacy helpers are not present on the watcher.""" assert not hasattr(file_watcher, attr_name) @pytest.mark.parametrize("name_key", ["test.glob_recursive", "test.direct_parent"]) def test_directory_watchers_use_recursive_globs( file_watcher, temp_component_files, name_key: str ): """Ensure directory watchers are configured with recursive "**/*" globs.""" mock_watcher_instance = Mock() watcher_class_mock = Mock(return_value=mock_watcher_instance) with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=watcher_class_mock, ): file_watcher.start_file_watching({name_key: temp_component_files["temp_dir"]}) assert watcher_class_mock.call_count == 1 assert watcher_class_mock.call_args.kwargs.get("glob_pattern") == "**/*" @pytest.mark.parametrize( "ignored_dir", ["node_modules", ".git", "__pycache__", ".cache", "coverage", "venv"], ) def test_ignores_noisy_directories_in_callbacks( file_watcher, temp_component_files, ignored_dir: str ): """Change events under common noisy directories must be ignored in callbacks.""" mock_watcher_instance = Mock() watcher_class_mock = Mock(return_value=mock_watcher_instance) with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=watcher_class_mock, ): file_watcher.start_file_watching( {"test.glob_ignore": temp_component_files["temp_dir"]} ) assert watcher_class_mock.call_count == 1 cb = watcher_class_mock.call_args.args[1] noisy_path = str( (temp_component_files["temp_dir"] / "js" / ignored_dir / "dep.js").resolve() ) cb(noisy_path) file_watcher._component_update_callback.assert_not_called() def test_restart_replaces_previous_watchers(file_watcher, tmp_path: Path): """Calling start_file_watching twice should restart and replace watchers and directories.""" mock_watcher_first = Mock() mock_watcher_second = Mock() # The watcher class will return different instances on subsequent calls watcher_class_mock = Mock(side_effect=[mock_watcher_first, mock_watcher_second]) with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=watcher_class_mock, ): # First start with one root first_root = tmp_path / "first" first_root.mkdir() file_watcher.start_file_watching({"comp.first": first_root}) assert file_watcher.is_watching_active assert len(file_watcher._path_watchers) == 1 assert list(file_watcher._watched_directories.keys()) == [ str(first_root.resolve()) ] # Now restart with a different root; previous watcher should be closed and replaced second_root = tmp_path / "second" second_root.mkdir() file_watcher.start_file_watching({"comp.second": second_root}) # The first watcher should have been closed by the restart mock_watcher_first.close.assert_called_once() # We should have exactly one current watcher, and directories should reflect the new root assert file_watcher.is_watching_active assert len(file_watcher._path_watchers) == 1 assert list(file_watcher._watched_directories.keys()) == [ str(second_root.resolve()) ] def test_noop_path_watcher_short_circuits_and_stays_inactive( file_watcher, tmp_path: Path ): """When NoOpPathWatcher is returned, we should not create watchers or mark active.""" # Import NoOpPathWatcher to use identity comparison in code under test from streamlit.watcher.path_watcher import NoOpPathWatcher # Patch to return NoOpPathWatcher with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=NoOpPathWatcher, ): root = tmp_path / "comp" root.mkdir() file_watcher.start_file_watching({"comp": root}) # Should remain inactive and not register any watchers or directories assert not file_watcher.is_watching_active assert file_watcher._path_watchers == [] assert file_watcher._watched_directories == {} def test_start_failure_rolls_back_and_leaves_no_watchers(file_watcher, tmp_path: Path): """If creating a watcher fails mid-setup, previously created watchers are closed and no state is committed.""" # Prepare two directories to trigger two watcher creations dir_a = tmp_path / "a" dir_b = tmp_path / "b" dir_a.mkdir() dir_b.mkdir() first_watcher = Mock() def ctor(*args, **kwargs): if ctor.calls == 0: ctor.calls += 1 return first_watcher raise RuntimeError("boom") ctor.calls = 0 with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=ctor, ): # Should not raise; internal code logs and rolls back file_watcher.start_file_watching( { "c1": dir_a, "c2": dir_b, } ) # Rollback: no watchers kept, not active, no directories remembered, roots not set assert not file_watcher.is_watching_active assert file_watcher._path_watchers == [] assert file_watcher._watched_directories == {} assert file_watcher._asset_watch_roots == {} # The partially created watcher must be closed during rollback first_watcher.close.assert_called_once() def test_asset_roots_only_committed_after_success(file_watcher, tmp_path: Path): """Roots should be committed only on successful watcher setup; on failure, they remain empty.""" root = tmp_path / "comp" root.mkdir() def ctor(*args, **kwargs): raise RuntimeError("fail") with patch( "streamlit.watcher.path_watcher.get_default_path_watcher_class", return_value=ctor, ): file_watcher.start_file_watching({"comp": root}) assert not file_watcher.is_watching_active assert file_watcher._path_watchers == [] assert file_watcher._watched_directories == {} # Roots should not be committed on failure assert file_watcher._asset_watch_roots == {}
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_component_file_watcher.py", "license": "Apache License 2.0", "lines": 313, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/components/v2/component_registry.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Component registry for Custom Components v2. This module defines the data model and in-memory registry for Custom Components v2. During development, component assets (JS/CSS/HTML) may change on disk as build tools produce new outputs. See Also -------- - :class:`streamlit.components.v2.component_file_watcher.ComponentFileWatcher` for directory watching and change notifications. """ from __future__ import annotations import os import threading from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Final from streamlit.components.v2.component_path_utils import ComponentPathUtils from streamlit.errors import StreamlitComponentRegistryError from streamlit.logger import get_logger if TYPE_CHECKING: from collections.abc import MutableMapping _LOGGER: Final = get_logger(__name__) @dataclass(frozen=True) class BidiComponentDefinition: """Definition of a bidirectional component V2. The definition holds inline content or file references for HTML, CSS, and JavaScript, plus metadata used by the runtime to serve assets. When CSS/JS are provided as file paths, their asset-dir-relative URLs are exposed via ``css_url`` and ``js_url`` (or can be overridden with ``css_asset_relative_path``/``js_asset_relative_path``). Parameters ---------- name : str A short, descriptive name for the component. html : str or None, optional HTML content as a string. css : str or None, optional Inline CSS content or an absolute/relative path to a ``.css`` file. Relative paths are interpreted as asset-dir-relative and validated to reside within the component's ``asset_dir``. Absolute paths are rejected by the API. js : str or None, optional Inline JavaScript content or an absolute/relative path to a ``.js`` file. Relative paths are interpreted as asset-dir-relative and validated to reside within the component's ``asset_dir``. Absolute paths are rejected by the API. css_asset_relative_path : str or None, optional Asset-dir-relative URL path to use when serving the CSS file. If not provided, the filename from ``css`` is used when ``css`` is file-backed. js_asset_relative_path : str or None, optional Asset-dir-relative URL path to use when serving the JS file. If not provided, the filename from ``js`` is used when ``js`` is file-backed. """ name: str html: str | None = None css: str | None = None js: str | None = None # Store processed content and metadata _has_css_path: bool = field(default=False, init=False, repr=False) _has_js_path: bool = field(default=False, init=False, repr=False) _source_paths: dict[str, str] = field(default_factory=dict, init=False, repr=False) # Asset-dir-relative paths used for frontend loading. These represent the # URL path segment under the component's declared asset_dir (e.g. "build/index.js") # and are independent of the on-disk absolute file path stored in css/js. css_asset_relative_path: str | None = None js_asset_relative_path: str | None = None def __post_init__(self) -> None: # Keep track of source paths for content loaded from files source_paths = {} # Store CSS and JS paths if provided is_css_path, css_path = self._is_file_path(self.css) is_js_path, js_path = self._is_file_path(self.js) if css_path: source_paths["css"] = os.path.dirname(css_path) if js_path: source_paths["js"] = os.path.dirname(js_path) object.__setattr__(self, "_has_css_path", is_css_path) object.__setattr__(self, "_has_js_path", is_js_path) object.__setattr__(self, "_source_paths", source_paths) # Allow empty definitions to support manifest-registered components that # declare only an asset sandbox (asset_dir) without inline or file-backed # entry content. Runtime API calls can later provide js/css/html. def _is_file_path(self, content: str | None) -> tuple[bool, str | None]: """Determine whether ``content`` is a filesystem path and resolve it. For string inputs that look like paths (contain separators, prefixes, or have common asset extensions), values are normally provided by the v2 public API, which resolves and validates asset-dir-relative inputs and passes absolute paths here. When this dataclass is constructed internally, callers must supply already-resolved absolute paths that have passed the same validation rules upstream. Relative paths are not accepted here. Parameters ---------- content : str or None The potential inline content or path. Returns ------- tuple[bool, str | None] ``(is_path, abs_path)`` where ``is_path`` indicates whether the input was treated as a path and ``abs_path`` is the resolved absolute path if a path, otherwise ``None``. Raises ------ ValueError If ``content`` is treated as a path but the file does not exist, or if a non-absolute, path-like string is provided. """ if content is None: return False, None # Determine if it's a file path or inline content for strings if isinstance(content, str): stripped = content.strip() is_likely_path = not ComponentPathUtils.looks_like_inline_content(stripped) if is_likely_path: if os.path.isabs(content): abs_path = content if not os.path.exists(abs_path): raise ValueError(f"File does not exist: {abs_path}") return True, abs_path # Relative, path-like strings are not accepted at this layer. raise ValueError( "Relative file paths are not accepted in BidiComponentDefinition; " "pass absolute, pre-validated paths from the v2 API." ) # If we get here, it's content, not a path return False, None @property def is_placeholder(self) -> bool: """Return True if this definition is a placeholder (no content). Placeholders are typically created during the manifest scanning phase when we discover a component's existence but haven't yet loaded its content via the public API. """ return self.html is None and self.css is None and self.js is None @property def css_url(self) -> str | None: """Return the asset-dir-relative URL path for CSS when file-backed. When present, servers construct ``/_stcore/bidi-components/<component>/<css_url>`` using this value. If ``css_asset_relative_path`` is specified, it takes precedence over the filename derived from ``css``. """ return self._derive_asset_url( has_path=self._has_css_path, value=self.css, override=self.css_asset_relative_path, ) @property def js_url(self) -> str | None: """Return the asset-dir-relative URL path for JS when file-backed. When present, servers construct ``/_stcore/bidi-components/<component>/<js_url>`` using this value. If ``js_asset_relative_path`` is specified, it takes precedence over the filename derived from ``js``. """ return self._derive_asset_url( has_path=self._has_js_path, value=self.js, override=self.js_asset_relative_path, ) def _derive_asset_url( self, *, has_path: bool, value: str | None, override: str | None ) -> str | None: """Compute asset-dir-relative URL for a file-backed asset. Parameters ---------- has_path Whether the value refers to a file path. value The css/js field value (inline string or path). override Optional explicit asset-dir-relative override. Returns ------- str or None The derived URL path or ``None`` if not file-backed. """ if not has_path: return None # Prefer explicit URL override if provided (relative to asset_dir) if override: return override # Fallback: preserve relative subpath if the provided path is relative; # otherwise default to the basename for absolute paths. Normalize # leading "./" to avoid awkward prefixes in URLs. path_str = str(value) if os.path.isabs(path_str): return os.path.basename(path_str) norm = path_str.replace("\\", "/").removeprefix("./") # If there's a subpath remaining, preserve it; otherwise use basename return norm if "/" in norm else os.path.basename(norm) @property def css_content(self) -> str | None: """Return inline CSS content or ``None`` if file-backed or missing.""" if self._has_css_path or self.css is None: return None # Return as string if it's not a path return str(self.css) @property def js_content(self) -> str | None: """Return inline JavaScript content or ``None`` if file-backed or missing.""" if self._has_js_path or self.js is None: return None # Return as string if it's not a path return str(self.js) @property def html_content(self) -> str | None: """Return inline HTML content or ``None`` if not provided.""" return self.html @property def source_paths(self) -> dict[str, str]: """Return source directories for file-backed CSS/JS content. The returned mapping contains keys like ``"js"`` and ``"css"`` with the directory path from which each was loaded. """ return self._source_paths class BidiComponentRegistry: """Registry for bidirectional components V2. The registry stores and updates :class:`BidiComponentDefinition` instances in a thread-safe mapping guarded by a lock. """ def __init__(self) -> None: """Initialize the component registry with an empty, thread-safe store.""" self._components: MutableMapping[str, BidiComponentDefinition] = {} self._lock = threading.Lock() def register_components_from_definitions( self, component_definitions: dict[str, dict[str, Any]] ) -> None: """Register components from processed definition data. Parameters ---------- component_definitions : dict[str, dict[str, Any]] Mapping from component identifier to definition data. """ with self._lock: # Register all component definitions for comp_name, comp_def_data in component_definitions.items(): # Validate required keys and gracefully handle optional ones. name = comp_def_data.get("name") if not name: raise ValueError( f"Component definition for key '{comp_name}' is missing required 'name' field" ) definition = BidiComponentDefinition( name=name, js=comp_def_data.get("js"), css=comp_def_data.get("css"), html=comp_def_data.get("html"), css_asset_relative_path=comp_def_data.get( "css_asset_relative_path" ), js_asset_relative_path=comp_def_data.get("js_asset_relative_path"), ) self._components[comp_name] = definition _LOGGER.debug( "Registered component %s from processed definitions", comp_name ) def register(self, definition: BidiComponentDefinition) -> None: """Register or overwrite a component definition by name. This method is the primary entry point for adding a component to the registry. It is used when a component is first declared via the public API (e.g., ``st.components.v2.component``). If a component with the same name already exists (e.g., a placeholder from a manifest scan), it is overwritten. A warning is logged if the new definition differs from the old one to alert developers of potential conflicts. Parameters ---------- definition : BidiComponentDefinition The component definition to store. """ # Register the definition with self._lock: name = definition.name if name in self._components: existing_definition = self._components[name] # Check if the existing definition is different and NOT a placeholder. # We expect placeholders (from manifest scanning) to be overwritten # by the actual definition from the script execution, so we silence # the warning in that specific case. if ( existing_definition != definition and not existing_definition.is_placeholder ): _LOGGER.warning( "Component %s is already registered. Overwriting " "previous definition. This may lead to unexpected behavior " "if different modules register the same component name with " "different definitions.", name, ) self._components[name] = definition _LOGGER.debug("Registered component %s", name) def get(self, name: str) -> BidiComponentDefinition | None: """Return a component definition by name, or ``None`` if not found. Parameters ---------- name : str Component name to retrieve. Returns ------- BidiComponentDefinition or None The component definition if present, otherwise ``None``. """ with self._lock: return self._components.get(name) def unregister(self, name: str) -> None: """Remove a component definition from the registry. Primarily useful for tests and dynamic scenarios. Parameters ---------- name : str Component name to unregister. """ with self._lock: if name in self._components: del self._components[name] _LOGGER.debug("Unregistered component %s", name) def clear(self) -> None: """Clear all component definitions from the registry.""" with self._lock: self._components.clear() _LOGGER.debug("Cleared all components from registry") def update_component(self, definition: BidiComponentDefinition) -> None: """Update (replace) a stored component definition by name. This method provides a stricter way to update a component definition and is used for internal processes like file-watcher updates. Unlike ``register``, it will raise an error if the component is not already present in the registry. This ensures that background processes can only modify components that have been explicitly defined in the current session, preventing race conditions or unexpected behavior where a file-watcher event might try to update a component that has since been unregistered. Callers must supply a fully validated :class:`BidiComponentDefinition`. The registry replaces the stored definition under ``definition.name`` in a thread-safe manner. Parameters ---------- definition : BidiComponentDefinition The fully-resolved component definition to store. """ with self._lock: name = definition.name if name not in self._components: raise StreamlitComponentRegistryError( f"Cannot update unregistered component: {name}" ) self._components[name] = definition _LOGGER.debug("Updated component definition for %s", name)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/component_registry.py", "license": "Apache License 2.0", "lines": 360, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_registry.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import tempfile import threading import time from pathlib import Path from unittest.mock import MagicMock, patch import pytest from streamlit.components.v2 import component from streamlit.components.v2.component_manager import BidiComponentManager from streamlit.components.v2.component_path_utils import ComponentPathUtils from streamlit.components.v2.component_registry import ( BidiComponentDefinition, BidiComponentRegistry, ) from streamlit.components.v2.manifest_scanner import ComponentConfig, ComponentManifest from streamlit.errors import StreamlitAPIException, StreamlitComponentRegistryError def _mk_file(path: os.PathLike[str] | str, content: bytes | str = b"x") -> str: """Create a file and return its absolute path. Parameters ---------- path Path to write. Parent directories are created if they don't exist. content Bytes or text to write to the file. Defaults to a single ``x`` byte. Returns ------- str Absolute path to the created file. """ p = os.fspath(path) os.makedirs(os.path.dirname(p), exist_ok=True) mode = "wb" if isinstance(content, (bytes, bytearray)) else "w" with open(p, mode) as f: f.write(content) return os.path.abspath(p) def test_path_classification_and_resolution(tmp_path) -> None: """Verify classification at dataclass layer: absolute paths vs inline. - Accepts absolute file paths (post-validation upstream). - Rejects relative, path-like strings. - Treats inline-like content as inline. """ base_dir = tmp_path / "base" caller_dir = base_dir / "pkg" / "subpkg" caller_file = caller_dir / "fakecaller.py" # Files to be resolved relative to caller_dir style_css = caller_dir / "style.css" assets_js = caller_dir / "assets" / "app.js" bare_js = caller_dir / "script.js" upper_js = base_dir / "pkg" / "upper.js" # resolves via ../upper.js from subpkg _mk_file(caller_file) _mk_file(style_css) _mk_file(assets_js) _mk_file(bare_js) _mk_file(upper_js) d1 = BidiComponentDefinition(name="c1", css=os.fspath(style_css)) assert d1._has_css_path is True assert d1.source_paths["css"] == os.path.dirname(os.fspath(style_css)) assert d1.css_url == "style.css" with pytest.raises(ValueError, match=r"Relative file paths are not accepted"): BidiComponentDefinition(name="c_bad", js="../upper.js") # Accept: path with separator d2 = BidiComponentDefinition(name="c2", js=os.fspath(assets_js)) assert d2._has_js_path is True assert d2.source_paths["js"] == os.path.dirname(os.fspath(assets_js)) # Reject: bare filename with known extension (relative path-like) with pytest.raises(ValueError, match=r"Relative file paths are not accepted"): BidiComponentDefinition(name="c3", js="script.js") # Inline-like content is not treated as a path d4 = BidiComponentDefinition( name="c4", html="<div>Hi</div>", css=".class { color: red; }", js="function f() { return 1; }", ) assert d4._has_css_path is False assert d4._has_js_path is False assert d4.css_content == ".class { color: red; }" assert d4.js_content == "function f() { return 1; }" assert d4.html_content == "<div>Hi</div>" @pytest.mark.parametrize( ("overrides", "expected_css_url", "expected_js_url"), [ ( { "css_asset_relative_path": "assets/bundle.css", "js_asset_relative_path": "build/main.mjs", }, "assets/bundle.css", "build/main.mjs", ), ({}, "style.css", "main.js"), ], ) def test_asset_url_overrides_and_defaults( tmp_path, monkeypatch, overrides: dict[str, str], expected_css_url: str, expected_js_url: str, ) -> None: """Verify that asset URL overrides take precedence over default filenames.""" caller_dir = tmp_path / "caller" caller_file = caller_dir / "fakecaller.py" css_file = caller_dir / "style.css" js_file = caller_dir / "main.js" _mk_file(caller_file) _mk_file(css_file) _mk_file(js_file) d = BidiComponentDefinition( name="c", css=os.fspath(css_file), js=os.fspath(js_file), **overrides, ) assert d.css_url == expected_css_url assert d.js_url == expected_js_url @pytest.mark.parametrize( ("css_input", "js_input", "expected_css_url", "expected_js_url"), [ ( "build/static/css/main.css", "build/static/js/main.js", "build/static/css/main.css", "build/static/js/main.js", ), ( "styles/bundle.css", "main.js", "styles/bundle.css", "main.js", ), ], ) def test_default_asset_url_preserves_subpath( tmp_path, monkeypatch, css_input: str, js_input: str, expected_css_url: str, expected_js_url: str, ) -> None: """Verify that default asset URLs preserve subpaths and simple filenames.""" caller_dir = tmp_path / "caller" caller_file = caller_dir / "fakecaller.py" css_file = caller_dir / css_input js_file = caller_dir / js_input _mk_file(caller_file) _mk_file(css_file) _mk_file(js_file) d = BidiComponentDefinition( name="c", css=os.fspath(css_file), js=os.fspath(js_file), css_asset_relative_path=css_input, js_asset_relative_path=js_input, ) assert d.css_url == expected_css_url assert d.js_url == expected_js_url def test_register_components_respects_asset_overrides(tmp_path: Path) -> None: """Verify that the registry preserves asset URL overrides on registration.""" css_path = _mk_file(tmp_path / "c" / "style.css") js_path = _mk_file(tmp_path / "c" / "main.js") reg = BidiComponentRegistry() reg.register_components_from_definitions( { "comp": { "name": "comp", "html": None, "css": css_path, "js": js_path, "css_asset_relative_path": "assets/styles.css", "js_asset_relative_path": "build/app.js", } } ) d = reg.get("comp") assert d is not None assert d.css_url == "assets/styles.css" assert d.js_url == "build/app.js" def test_update_component_merge_enforcement() -> None: """Verify that updates preserve missing fields and enforce name matching.""" reg = BidiComponentRegistry() # Initial inline definition d0 = BidiComponentDefinition(name="comp", html=None, css="orig-css", js="orig-js") reg.register(d0) # Attempt to update only js and css override d1 = BidiComponentDefinition( name="comp", html=None, css="new-css", js="new-js", ) reg.update_component(d1) d = reg.get("comp") assert d is not None assert d.name == "comp" assert d.html_content is None # css and js are updated assert d.css_content == "new-css" assert d.js_content == "new-js" def test_update_component_replaces_definition() -> None: """Verify that `update_component` replaces the stored definition by name.""" reg = BidiComponentRegistry() # Initial inline definition d0 = BidiComponentDefinition(name="comp", html=None, css="orig-css", js="orig-js") reg.register(d0) # New fully-validated definition (simulating resolver output) d1 = BidiComponentDefinition( name="comp", html="<div></div>", css="new-css", js="new-js", css_asset_relative_path="x.css", ) reg.update_component(d1) d = reg.get("comp") assert d is not None assert d.name == "comp" assert d.html_content == "<div></div>" assert d.css_content == "new-css" assert d.js_content == "new-js" assert d.css_asset_relative_path == "x.css" def test_update_component_can_clear_fields_via_none() -> None: """Verify that passing None to `update_component` clears fields.""" reg = BidiComponentRegistry() d0 = BidiComponentDefinition( name="comp", html="<div>keep?</div>", css="inline-css", js="inline-js", ) reg.register(d0) # Provide a definition that clears css/js and html explicitly via None d1 = BidiComponentDefinition(name="comp", html=None, css=None, js=None) reg.update_component(d1) d = reg.get("comp") assert d is not None assert d.html_content is None assert d.css_content is None assert d.js_content is None def test_update_component_raises_for_unregistered_definition() -> None: """Verify `update_component` raises for an unregistered definition.""" reg = BidiComponentRegistry() d = BidiComponentDefinition(name="unknown", html=None, css=None, js=None) with pytest.raises( StreamlitComponentRegistryError, match=r"^Cannot update unregistered component: unknown$", ): reg.update_component(d) @pytest.fixture def temp_test_files() -> dict: """Create a temporary directory with test files for definition tests.""" temp_dir = tempfile.TemporaryDirectory() # Create test files js_path = os.path.join(temp_dir.name, "index.js") with open(js_path, "w", encoding="utf-8") as f: f.write("console.log('test');") html_path = os.path.join(temp_dir.name, "index.html") with open(html_path, "w", encoding="utf-8") as f: f.write("<div>Test</div>") css_path = os.path.join(temp_dir.name, "styles.css") with open(css_path, "w", encoding="utf-8") as f: f.write("div { color: blue; }") yield { "temp_dir": temp_dir, "js_path": js_path, "html_path": html_path, "css_path": css_path, } temp_dir.cleanup() @pytest.fixture def temp_manager_setup() -> dict: """Create a temporary directory and manager for BidiComponentManager tests.""" temp_dir = tempfile.TemporaryDirectory() component_manager = BidiComponentManager() # Create test files js_path = os.path.join(temp_dir.name, "index.js") with open(js_path, "w", encoding="utf-8") as f: f.write("console.log('test');") yield { "temp_dir": temp_dir, "component_manager": component_manager, "js_path": js_path, } temp_dir.cleanup() def test_string_content(temp_test_files) -> None: """Test component instantiation with direct string content.""" comp = BidiComponentDefinition( name="test", html="<div>Hello</div>", css=".div { color: red; }", js="console.log('hello');", ) assert comp.html_content == "<div>Hello</div>" assert comp.css_content == ".div { color: red; }" assert comp.js_content == "console.log('hello');" assert comp.css_url is None assert comp.js_url is None assert comp.source_paths == {} def test_newline_strings_treated_as_inline() -> None: """Verify that strings with newlines are treated as inline content.""" multi_line_js = "export default function() {\n console.log('hi');\n}" multi_line_css = ".root {\n color: red;\n}" multi_line_html = "<div>\n <span>hi</span>\n</div>" comp = BidiComponentDefinition( name="newline_test", html=multi_line_html, css=multi_line_css, js=multi_line_js, ) # Inline content should be exposed via *_content and have no URLs assert comp.html_content == multi_line_html assert comp.css_content == multi_line_css assert comp.js_content == multi_line_js assert comp.css_url is None assert comp.js_url is None assert comp.source_paths == {} def test_file_path_content(temp_test_files) -> None: """Test component instantiation with absolute file path content.""" comp = BidiComponentDefinition( name="test", js=temp_test_files["js_path"], html="<div>Inline HTML</div>", # HTML should be a string, not a path css=temp_test_files["css_path"], ) assert comp.html_content == "<div>Inline HTML</div>" assert comp.css_content is None # CSS content is None because it's a path assert comp.js_content is None # JS content is None because it's a path # Check URLs are generated for path resources assert comp.css_url == f"{os.path.basename(temp_test_files['css_path'])}" assert comp.js_url == f"{os.path.basename(temp_test_files['js_path'])}" # Check source paths assert len(comp.source_paths) == 2 assert comp.source_paths["css"] == os.path.dirname(temp_test_files["css_path"]) assert comp.source_paths["js"] == os.path.dirname(temp_test_files["js_path"]) assert "html" not in comp.source_paths def test_mixed_content(temp_test_files) -> None: """Test component instantiation with mixed string and file content.""" comp = BidiComponentDefinition( name="test", js=temp_test_files["js_path"], html="<div>Inline HTML</div>", css="div { color: green; }", ) assert comp.html_content == "<div>Inline HTML</div>" assert comp.css_content == "div { color: green; }" assert comp.js_content is None # JS content is None because it's a path assert comp.css_url is None # No URL for inline CSS assert comp.js_url == f"{os.path.basename(temp_test_files['js_path'])}" assert len(comp.source_paths) == 1 assert comp.source_paths["js"] == os.path.dirname(temp_test_files["js_path"]) def test_public_api_path_object_rejection() -> None: """Verify the public API rejects non-string path-like objects.""" from pathlib import Path with pytest.raises(StreamlitAPIException) as exc_info: component("test", js=Path("test.js")) msg = str(exc_info.value) assert "string or None" in msg assert "string path or glob" in msg with pytest.raises(StreamlitAPIException) as exc_info: component("test", css=Path("test.css")) msg = str(exc_info.value) assert "string or None" in msg assert "string path or glob" in msg # Still raise for other invalid types with pytest.raises(StreamlitAPIException): component("test", js=123) # Integer instead of string/Path with pytest.raises(StreamlitAPIException): component("test", css=["invalid", "list"]) # List instead of string/Path def test_component_mount_ignores_isolate_styles_kwarg() -> None: """Verify mount-time isolate_styles is ignored (and does not raise). Without the mount-time kwarg being stripped, the mount callable would end up calling ``st._bidi_component(..., isolate_styles=<from component()>, **kwargs)`` where ``kwargs`` also contains ``isolate_styles``. That would raise a ``TypeError`` about multiple values for the same keyword argument before `_bidi_component` runs. """ import streamlit as st on_clicked_change = MagicMock(name="on_clicked_change") with ( patch.object( st.components.v2, "_register_component", return_value="test_component" ), patch.object( st, "_bidi_component", return_value=MagicMock() ) as mock_bidi_component, ): mount = component( "test_component", js="console.log('test');", isolate_styles=False, ) mount( key="k", isolate_styles=True, # legacy-style kwarg should be dropped silently on_clicked_change=on_clicked_change, ) args, kwargs = mock_bidi_component.call_args assert args[0] == "test_component" assert kwargs["isolate_styles"] is False assert kwargs["key"] == "k" assert kwargs["on_clicked_change"] is on_clicked_change def test_register_from_manifest_basic(temp_manager_setup) -> None: """Test basic manifest registration with a single component. Note ---- JS/CSS entries in the manifest are ignored. """ setup = temp_manager_setup # Create component files in package root package_root = Path(setup["temp_dir"].name) # Files may exist but are not read from manifest anymore (package_root / "component.js").write_text( "export default function() { console.log('basic test'); }" ) (package_root / "styles.css").write_text(".test { color: blue; }") manifest = ComponentManifest( name="test_package", version="1.0.0", components=[ ComponentConfig( name="basic_component", ) ], ) setup["component_manager"].register_from_manifest(manifest, package_root) # Check component was registered component = setup["component_manager"].get("test_package.basic_component") assert component is not None assert component.name == "test_package.basic_component" # Assert that html/js/css are None because they must be provided via the # st.components.v2.component() API assert component.html_content is None assert component.js_content is None assert component.css_content is None # Check metadata was stored assert ( setup["component_manager"].get_metadata("test_package.basic_component") == manifest ) def test_register_from_manifest_multiple_components(temp_manager_setup) -> None: """Test manifest registration with multiple components.""" setup = temp_manager_setup package_root = Path(setup["temp_dir"].name) # Create files (not used by manifest anymore) (package_root / "comp1.js").write_text("console.log('component 1');") (package_root / "comp1.css").write_text(".comp1 { background: red; }") (package_root / "comp2.js").write_text("console.log('component 2');") manifest = ComponentManifest( name="multi_package", version="2.0.0", components=[ ComponentConfig( name="component_one", ), ComponentConfig( name="component_two", ), ], ) setup["component_manager"].register_from_manifest(manifest, package_root) # Check first component was registered comp1 = setup["component_manager"].get("multi_package.component_one") assert comp1 is not None assert comp1.name == "multi_package.component_one" assert comp1.html_content is None assert comp1.js_content is None assert comp1.css_content is None # Check second component was registered comp2 = setup["component_manager"].get("multi_package.component_two") assert comp2 is not None assert comp2.name == "multi_package.component_two" assert comp2.html_content is None assert comp2.js_content is None assert comp2.css_content is None # Check both components have same manifest metadata assert ( setup["component_manager"].get_metadata("multi_package.component_one") == manifest ) assert ( setup["component_manager"].get_metadata("multi_package.component_two") == manifest ) def test_register_from_manifest_minimal_component(temp_manager_setup) -> None: """Test manifest registration with a minimal component (only HTML).""" setup = temp_manager_setup package_root = Path(setup["temp_dir"].name) manifest = ComponentManifest( name="minimal_package", version="0.1.0", components=[ComponentConfig(name="html_only")], ) setup["component_manager"].register_from_manifest(manifest, package_root) # Check component was registered component = setup["component_manager"].get("minimal_package.html_only") assert component is not None assert component.name == "minimal_package.html_only" assert component.html_content is None assert component.js_content is None assert component.css_content is None # Check metadata assert ( setup["component_manager"].get_metadata("minimal_package.html_only") == manifest ) def test_register_from_manifest_empty_components(temp_manager_setup) -> None: """Test that manifest registration handles an empty components list.""" setup = temp_manager_setup package_root = Path(setup["temp_dir"].name) manifest = ComponentManifest( name="empty_package", version="1.0.0", components=[], ) setup["component_manager"].register_from_manifest(manifest, package_root) def test_register_from_manifest_overwrites_existing(temp_manager_setup) -> None: """Verify that manifest registration overwrites existing components.""" setup = temp_manager_setup package_root = Path(setup["temp_dir"].name) js_file = package_root / "component.js" js_file.write_text("console.log('original');") # Register first version manifest1 = ComponentManifest( name="test_package", version="1.0.0", components=[ ComponentConfig( name="component", ) ], ) setup["component_manager"].register_from_manifest(manifest1, package_root) # Check first registration component = setup["component_manager"].get("test_package.component") assert component.html_content is None # Register updated version js_file.write_text("console.log('updated');") manifest2 = ComponentManifest( name="test_package", version="2.0.0", components=[ ComponentConfig( name="component", ) ], ) with patch("streamlit.logger.get_logger") as mock_logger: setup["component_manager"].register_from_manifest(manifest2, package_root) # Should not log warning for manifest registration (different from manual registration) mock_logger.return_value.warning.assert_not_called() # Check component was updated updated_component = setup["component_manager"].get("test_package.component") assert updated_component.html_content is None assert ( setup["component_manager"].get_metadata("test_package.component") == manifest2 ) def test_register_from_manifest_thread_safety(temp_manager_setup) -> None: """Verify that manifest registration is thread-safe.""" setup = temp_manager_setup package_root = Path(setup["temp_dir"].name) js_file = package_root / "thread_test.js" js_file.write_text("console.log('thread test');") results = [] errors = [] def register_manifest(thread_id: int) -> None: try: manifest = ComponentManifest( name=f"thread_package_{thread_id}", version="1.0.0", components=[ ComponentConfig( name="thread_component", ) ], ) # Add small delay to increase chance of race conditions time.sleep(0.01) setup["component_manager"].register_from_manifest(manifest, package_root) results.append(thread_id) except Exception as e: errors.append(e) # Create multiple threads threads = [] for i in range(5): thread = threading.Thread(target=register_manifest, args=(i,)) threads.append(thread) thread.start() # Wait for all threads to complete for thread in threads: thread.join() # Check all threads completed successfully assert len(errors) == 0 assert len(results) == 5 assert set(results) == {0, 1, 2, 3, 4} # Check all components were registered for i in range(5): component = setup["component_manager"].get( f"thread_package_{i}.thread_component" ) assert component is not None assert component.html_content is None def test_resolve_glob_pattern_direct() -> None: """Test the `ComponentPathUtils.resolve_glob_pattern` function directly.""" with tempfile.TemporaryDirectory() as temp_dir: package_root = Path(temp_dir) # Create test file test_file = os.path.join(temp_dir, "test-pattern.js") with open(test_file, "w", encoding="utf-8") as f: f.write("console.log('test');") # Test successful resolution resolved = ComponentPathUtils.resolve_glob_pattern("test-*.js", package_root) assert str(resolved.resolve()) == Path(test_file).resolve().as_posix() # Test no matches with pytest.raises(StreamlitComponentRegistryError) as exc_info: ComponentPathUtils.resolve_glob_pattern("nomatch-*.js", package_root) assert "No files found matching pattern" in str(exc_info.value) # Test multiple matches duplicate_file = os.path.join(temp_dir, "test-duplicate.js") with open(duplicate_file, "w", encoding="utf-8") as f: f.write("console.log('duplicate');") with pytest.raises(StreamlitComponentRegistryError) as exc_info: ComponentPathUtils.resolve_glob_pattern("test-*.js", package_root) assert "Multiple files found matching pattern" in str(exc_info.value) # Test path traversal protection with pytest.raises(StreamlitComponentRegistryError) as exc_info: ComponentPathUtils.resolve_glob_pattern("../outside.js", package_root) assert "Path traversal attempts are not allowed" in str(exc_info.value) # Test absolute path protection with pytest.raises(StreamlitComponentRegistryError) as exc_info: ComponentPathUtils.resolve_glob_pattern("/absolute/path.js", package_root) assert "Unsafe paths are not allowed" in str(exc_info.value) @pytest.fixture def component_manager(): """Create a fresh BidiComponentManager for testing.""" return BidiComponentManager() def test_basic_registration(component_manager) -> None: """Test basic component registration via `BidiComponentManager`.""" definition = BidiComponentDefinition( name="test_component", html="<div>Test</div>", js="console.log('test');", ) component_manager.register(definition) retrieved = component_manager.get("test_component") assert retrieved == definition def test_file_watching_state_tracking(component_manager) -> None: """Verify that file watching state is correctly tracked.""" # Initially, file watching should not be started assert not component_manager.is_file_watching_started # The state should remain consistent with the file watcher assert ( component_manager.is_file_watching_started == component_manager._file_watcher.is_watching_active ) def test_glob_pattern_resolution() -> None: """Test glob pattern resolution via `ComponentPathUtils`.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create test files (temp_path / "component.js").write_text("console.log('component');") (temp_path / "styles.css").write_text("body { color: red; }") # Test JS glob resolution js_path = ComponentPathUtils.resolve_glob_pattern("*.js", temp_path) assert js_path.name == "component.js" # Test CSS glob resolution css_path = ComponentPathUtils.resolve_glob_pattern("*.css", temp_path) assert css_path.name == "styles.css" def test_glob_pattern_multiple_matches_error() -> None: """Verify that multiple matches for a glob pattern raise an error.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create multiple matching files (temp_path / "component1.js").write_text("console.log('1');") (temp_path / "component2.js").write_text("console.log('2');") with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern("*.js", temp_path) def test_glob_pattern_no_matches_error() -> None: """Verify that no matches for a glob pattern raise an error.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern("*.js", temp_path) @patch("streamlit.watcher.path_watcher.get_default_path_watcher_class") def test_file_watching_starts(mock_path_watcher_class) -> None: """Verify that file watching starts correctly in.""" mock_watcher_instance = MagicMock() mock_path_watcher_class.return_value.return_value = mock_watcher_instance with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create test file js_file = temp_path / "component.js" js_file.write_text("console.log('test');") # Create mock manifest with glob pattern manifest = ComponentManifest( name="test_package", version="1.0.0", components=[ComponentConfig(name="test_component")], ) # Create manager and register from manifest manager = BidiComponentManager() manager.register_from_manifest(manifest, temp_path) # Start file watching manager.start_file_watching() # No watchers should be created from manifest-only data assert not manager.is_file_watching_started mock_path_watcher_class.return_value.assert_not_called() def test_security_validation() -> None: """Test security validation for file paths.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Test path traversal protection with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern("../malicious.js", temp_path) with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern("/etc/passwd", temp_path) @pytest.mark.parametrize( ("target_field", "second_args", "expect_present_field"), [ ("html", {"js": "export default function(){}"}, "js"), ("css", {"js": "export default function(){}"}, "js"), ("js", {"html": "<div>Updated</div>"}, "html"), ], ) def test_runtime_override_removes_field( monkeypatch, target_field, second_args, expect_present_field ) -> None: """Verify that removing a field in a subsequent registration clears it. We first register a component with multiple fields set. Then, we call the public API again omitting the target field. The registry should update the definition so that the target field is None, rather than preserving it. """ from streamlit.components.v2 import component as component_api from streamlit.components.v2.component_manager import BidiComponentManager manager = BidiComponentManager() # Patch the component API to use our local manager instance. monkeypatch.setattr( "streamlit.components.v2.get_bidi_component_manager", lambda: manager, ) # Initial registration includes all three fields to keep flexibility component_api( "my_component", html="<h1>Hello World</h1>", css=".title{color:red;}", js="export default function(){}", ) # Subsequent registration provides only a non-target field to keep valid component_api("my_component", **second_args) definition = manager.get("my_component") assert definition is not None # Target field should be cleared assert getattr(definition, target_field) is None # Provided non-target field should remain present assert getattr(definition, expect_present_field) is not None def test_register_overwrites_placeholder_without_warning() -> None: """Verify that overwriting a placeholder definition does not log a warning. This scenario happens when a component is first discovered via manifest scan (creating a placeholder) and then registered via the public API at runtime. """ reg = BidiComponentRegistry() name = "test_component" # 1. Register placeholder (mimics manifest scanning) placeholder = BidiComponentDefinition(name=name, html=None, css=None, js=None) reg.register(placeholder) assert placeholder.is_placeholder # 2. Register actual definition (mimics runtime API call) real_def = BidiComponentDefinition( name=name, html="<div>Content</div>", css=None, js=None, ) with patch("streamlit.components.v2.component_registry._LOGGER") as mock_logger: reg.register(real_def) # Verify registration succeeded stored = reg.get(name) assert stored == real_def assert not stored.is_placeholder # Verify NO warning was logged mock_logger.warning.assert_not_called() def test_register_overwrites_real_definition_with_warning() -> None: """Verify that overwriting a real definition LOGS a warning.""" reg = BidiComponentRegistry() name = "test_component" # 1. Register real definition def1 = BidiComponentDefinition( name=name, html="<div>Initial</div>", css=None, js=None ) reg.register(def1) # 2. Register different definition def2 = BidiComponentDefinition( name=name, html="<div>Updated</div>", css=None, js=None ) with patch("streamlit.components.v2.component_registry._LOGGER") as mock_logger: reg.register(def2) # Verify registration succeeded stored = reg.get(name) assert stored == def2 # Verify warning WAS logged mock_logger.warning.assert_called_once()
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_component_registry.py", "license": "Apache License 2.0", "lines": 814, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/components/v2/component_manifest_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import MutableMapping from pathlib import Path from streamlit.components.v2.manifest_scanner import ComponentManifest class ComponentManifestHandler: """Handles component registration from parsed ComponentManifest objects.""" def __init__(self) -> None: # Component metadata from pyproject.toml self._metadata: MutableMapping[str, ComponentManifest] = {} # Resolved asset roots keyed by fully-qualified component name self._asset_roots: MutableMapping[str, Path] = {} def process_manifest( self, manifest: ComponentManifest, package_root: Path ) -> dict[str, dict[str, Any]]: """Process a manifest and return component definitions to register. Parameters ---------- manifest : ComponentManifest The manifest to process package_root : Path The package root directory Returns ------- dict[str, dict[str, Any]] Dictionary mapping component names to their definitions Raises ------ StreamlitComponentRegistryError If a declared ``asset_dir`` does not exist, is not a directory, or resolves (after following symlinks) outside of ``package_root``. """ base_name = manifest.name component_definitions = {} # Process each component in the manifest for comp_config in manifest.components: comp_name = comp_config.name component_name = f"{base_name}.{comp_name}" # Parse and persist asset_dir if provided. This is the component's # root directory for all future file references. asset_root = comp_config.resolve_asset_root(package_root) if asset_root is not None: self._asset_roots[component_name] = asset_root # Create component definition data component_definitions[component_name] = { "name": component_name, } # Store metadata self._metadata[component_name] = manifest return component_definitions def get_metadata(self, component_name: str) -> ComponentManifest | None: """Get metadata for a specific component. Parameters ---------- component_name : str Fully-qualified component name (e.g., ``"package.component"``). Returns ------- ComponentManifest | None The manifest that declared this component, or ``None`` if unknown. """ return self._metadata.get(component_name) def get_asset_root(self, component_name: str) -> Path | None: """Get the absolute asset root directory for a component if declared. Parameters ---------- component_name : str Fully-qualified component name (e.g. "package.component"). Returns ------- Path | None Absolute path to the component's asset root if present, otherwise None. """ return self._asset_roots.get(component_name) def get_asset_watch_roots(self) -> dict[str, Path]: """Get a mapping of component names to their asset root directories. Returns ------- dict[str, Path] A shallow copy mapping fully-qualified component names to absolute asset root directories. """ return dict(self._asset_roots)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/component_manifest_handler.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/component_path_utils.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Security-hardened path utilities for Component v2. This module centralizes path validation and resolution logic used by the Component v2 registration and file access code paths. All helpers here are designed to prevent path traversal, insecure prefix checks, and symlink escapes outside of a declared package root. """ from __future__ import annotations from pathlib import Path from typing import Final from streamlit.errors import StreamlitComponentRegistryError from streamlit.logger import get_logger from streamlit.path_security import is_unsafe_path_pattern _LOGGER: Final = get_logger(__name__) class ComponentPathUtils: """Utility class for component path operations and security validation.""" @staticmethod def has_glob_characters(path: str) -> bool: """Check if a path contains glob pattern characters. Parameters ---------- path : str The path to check Returns ------- bool True if the path contains glob characters """ return any(char in path for char in ["*", "?", "[", "]"]) @staticmethod def validate_path_security(path: str) -> None: """Validate that a path doesn't contain security vulnerabilities. Parameters ---------- path : str The path to validate Raises ------ StreamlitComponentRegistryError If the path contains security vulnerabilities like path traversal attempts """ ComponentPathUtils._assert_relative_no_traversal(path, label="component paths") @staticmethod def resolve_glob_pattern(pattern: str, package_root: Path) -> Path: """Resolve a glob pattern to a single file path with security checks. Parameters ---------- pattern : str The glob pattern to resolve package_root : Path The package root directory for security validation Returns ------- Path The resolved file path Raises ------ StreamlitComponentRegistryError If zero or more than one file matches the pattern, or if security checks fail (path traversal attempts) """ # Ensure pattern is relative and doesn't contain path traversal attempts ComponentPathUtils._assert_relative_no_traversal(pattern, label="glob patterns") # Use glob from the package root so subdirectory patterns are handled correctly matching_files = list(package_root.glob(pattern)) # Ensure all matched files are within package_root (security check) validated_files = [] for file_path in matching_files: try: # Resolve to absolute path and check if it's within package_root resolved_path = file_path.resolve() package_root_resolved = package_root.resolve() # Check if the resolved path is within the package root using # pathlib's relative path check to avoid prefix-matching issues if not resolved_path.is_relative_to(package_root_resolved): _LOGGER.warning( "Skipping file outside package root: %s", resolved_path ) continue validated_files.append(resolved_path) except (OSError, ValueError) as e: _LOGGER.warning("Failed to resolve path %s: %s", file_path, e) continue # Ensure exactly one file matches if len(validated_files) == 0: raise StreamlitComponentRegistryError( f"No files found matching pattern '{pattern}' in package root {package_root}" ) if len(validated_files) > 1: file_list = ", ".join(str(f) for f in validated_files) raise StreamlitComponentRegistryError( f"Multiple files found matching pattern '{pattern}': {file_list}. " "Exactly one file must match the pattern." ) return Path(validated_files[0]) @staticmethod def _assert_relative_no_traversal(path: str, *, label: str) -> None: """Raise if ``path`` is absolute, contains traversal, or has unsafe patterns. This method uses the shared ``is_unsafe_path_pattern`` function to ensure consistent security checks across the codebase. The shared function also checks for additional patterns like null bytes, forward-slash UNC paths, and drive-relative paths (e.g., ``C:foo``). Parameters ---------- path : str Path string to validate. label : str Human-readable label used in error messages (e.g., "component paths"). """ if is_unsafe_path_pattern(path): # Determine appropriate error message based on pattern. # Use segment-based check to avoid false positives like "file..js" normalized = path.replace("\\", "/") segments = [seg for seg in normalized.split("/") if seg] if ".." in segments: raise StreamlitComponentRegistryError( f"Path traversal attempts are not allowed in {label}: {path}" ) raise StreamlitComponentRegistryError( f"Unsafe paths are not allowed in {label}: {path}" ) @staticmethod def ensure_within_root(abs_path: Path, root: Path, *, kind: str) -> None: """Ensure that abs_path is within root; raise if not. Parameters ---------- abs_path : Path Absolute file path root : Path Root directory path kind : str Human-readable descriptor for error messages (e.g., "js" or "css") Raises ------ StreamlitComponentRegistryError If the path cannot be resolved or if the resolved path does not reside within ``root`` after following symlinks. """ try: resolved = abs_path.resolve() root_resolved = root.resolve() except Exception as e: raise StreamlitComponentRegistryError( f"Failed to resolve {kind} path '{abs_path}': {e}" ) from e # Use Path.is_relative_to to avoid insecure prefix-based checks if not resolved.is_relative_to(root_resolved): raise StreamlitComponentRegistryError( f"{kind} path '{abs_path}' is outside the declared asset_dir '{root}'." ) @staticmethod def looks_like_inline_content(value: str) -> bool: r"""Heuristic to detect inline JS/CSS content strings. Treat a string as a file path ONLY if it looks path-like: - Does not contain newlines - Contains glob characters (*, ?, [, ]) - Starts with ./, /, or \ - Contains a path separator ("/" or "\\") - Or ends with a common asset extension like .js, .mjs, .cjs, or .css Otherwise, treat it as inline content. Parameters ---------- value : str The string to classify as inline content or a file path. Returns ------- bool True if ``value`` looks like inline content; False if it looks like a file path. """ s = value.strip() # If the value contains newlines, it's definitely inline content if "\n" in s or "\r" in s: return True # Glob patterns indicate path-like if ComponentPathUtils.has_glob_characters(s): return False # Obvious path prefixes if s.startswith(("./", "/", "\\")): return False # Any path separator if "/" in s or "\\" in s: return False return not (s.lower().endswith((".js", ".css", ".mjs", ".cjs")))
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/component_path_utils.py", "license": "Apache License 2.0", "lines": 196, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/streamlit/components/v2/manifest_scanner.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Discovery utilities for Component v2 manifests in installed packages. The scanner searches installed distributions for a ``pyproject.toml`` with ``[tool.streamlit.component]`` configuration and extracts the component manifests along with their package roots. The implementation prioritizes efficiency and safety by filtering likely candidates and avoiding excessive filesystem operations. """ from __future__ import annotations import importlib.metadata import importlib.util import os from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass from pathlib import Path from typing import Any, Final import toml from packaging import utils as packaging_utils from streamlit.components.v2.component_path_utils import ComponentPathUtils from streamlit.errors import StreamlitComponentRegistryError from streamlit.logger import get_logger _LOGGER: Final = get_logger(__name__) def _normalize_package_name(dist_name: str) -> str: """Normalize a distribution name to an importable package name. This helper converts hyphens to underscores to derive a best-effort importable module/package name from a distribution name. Parameters ---------- dist_name : str The distribution/project name (e.g., "my-awesome-component"). Returns ------- str The normalized package name suitable for import lookups (e.g., "my_awesome_component"). """ return dist_name.replace("-", "_") @dataclass class ComponentManifest: """Parsed component manifest data.""" name: str version: str components: list[ComponentConfig] @dataclass class ComponentConfig: """Structured configuration for a single component entry. Parameters ---------- name Component name as declared in ``pyproject.toml``. asset_dir Optional relative directory containing component assets. """ name: str asset_dir: str | None = None @staticmethod def from_dict(config: dict[str, Any]) -> ComponentConfig: """Create a ComponentConfig from a raw dict. Parameters ---------- config Raw component dictionary parsed from TOML. Returns ------- ComponentConfig Parsed and validated component configuration. """ name_value = config.get("name") if not isinstance(name_value, str) or not name_value: # Fail closed: invalid component entry raise ValueError("Component entry missing required 'name' field") asset_dir_value = config.get("asset_dir") if asset_dir_value is not None and not isinstance(asset_dir_value, str): # Fail closed: invalid asset_dir value raise ValueError("'asset_dir' must be a string") return ComponentConfig( name=name_value, asset_dir=asset_dir_value, ) @staticmethod def parse_or_none(config: dict[str, Any]) -> ComponentConfig | None: """Best-effort parse without raising; returns None on malformed input.""" try: return ComponentConfig.from_dict(config) except Exception as e: _LOGGER.debug("Skipping malformed component entry: %s", e) return None def resolve_asset_root(self, package_root: Path) -> Path | None: """Resolve and security-check the component's asset root directory. Parameters ---------- package_root : Path The root directory of the installed component package. Returns ------- Path | None Absolute, resolved path to the asset directory, or ``None`` if ``asset_dir`` is not declared. Raises ------ StreamlitComponentRegistryError If the declared directory does not exist, is not a directory, or resolves outside of ``package_root``. """ if self.asset_dir is None: return None # Validate the configured path string first ComponentPathUtils.validate_path_security(self.asset_dir) asset_root = (package_root / self.asset_dir).resolve() if not asset_root.exists() or not asset_root.is_dir(): raise StreamlitComponentRegistryError( f"Declared asset_dir '{self.asset_dir}' for component '{self.name}' " f"does not exist or is not a directory under package root '{package_root}'." ) # Ensure the resolved directory is within the package root after following symlinks ComponentPathUtils.ensure_within_root( abs_path=asset_root, root=package_root.resolve(), kind="asset_dir", ) return asset_root def _is_likely_streamlit_component_package( dist: importlib.metadata.Distribution, ) -> bool: """Check if a package is likely to contain streamlit components before expensive operations. This early filter reduces the number of packages that need file I/O operations from potentially hundreds down to just a few candidates. Parameters ---------- dist : importlib.metadata.Distribution The package distribution to check. Returns ------- bool True if the package might contain streamlit components, False otherwise. """ dist_name = dist.name if not isinstance(dist_name, str) or not dist_name: # We do not expect a distribution to be missing its name, be defensive # and fail closed to prevent runtime issues. return False name = dist_name.lower() summary = dist.metadata["Summary"].lower() if "Summary" in dist.metadata else "" # Filter 1: Package name suggests streamlit component if "streamlit" in name: return True # Filter 2: Package description mentions streamlit if "streamlit" in summary: return True # Filter 3: Check if package depends on streamlit try: # Check requires_dist for streamlit dependency requires_dist = dist.metadata.get_all("Requires-Dist") or [] for requirement in requires_dist: if requirement and "streamlit" in requirement.lower(): return True except Exception as e: # Don't fail on metadata parsing issues, but log for debugging purposes _LOGGER.debug( "Failed to parse package metadata for streamlit component detection: %s", e ) # Filter 4: Check if this is a known streamlit ecosystem package # Common patterns in streamlit component package names. Use anchored checks to # avoid matching unrelated packages like "test-utils". return name.startswith(("streamlit-", "streamlit_", "st-", "st_")) def _find_package_pyproject_toml(dist: importlib.metadata.Distribution) -> Path | None: """Find ``pyproject.toml`` for a package. Handles both regular and editable installs. The function uses increasingly permissive strategies to locate the file while validating that the file belongs to the given distribution. Parameters ---------- dist : importlib.metadata.Distribution The package distribution to find pyproject.toml for. Returns ------- Path | None Path to the ``pyproject.toml`` file if found, otherwise ``None``. """ package_name = _normalize_package_name(dist.name) # Try increasingly permissive strategies for finder in ( _pyproject_via_read_text, _pyproject_via_dist_files, lambda d: _pyproject_via_import_spec(d, package_name), ): result = finder(dist) if result is not None: return result return None def _pyproject_via_read_text(dist: importlib.metadata.Distribution) -> Path | None: """Locate pyproject.toml using the distribution's read_text + nearby files. This works for many types of installations including some editable ones. """ package_name = _normalize_package_name(dist.name) try: if hasattr(dist, "read_text"): pyproject_content = dist.read_text("pyproject.toml") if pyproject_content and dist.files: # Found content, now find the actual file path # Look for a reasonable file to get the directory for file in dist.files: if "__init__.py" in str(file) or ".py" in str(file): try: file_path = Path(str(dist.locate_file(file))) # Check nearby directories for pyproject.toml current_dir = file_path.parent # Check current directory and parent for search_dir in [current_dir, current_dir.parent]: pyproject_path = search_dir / "pyproject.toml" if ( pyproject_path.exists() and _validate_pyproject_for_package( pyproject_path, dist.name, package_name, ) ): return pyproject_path # Stop after first reasonable file break except Exception: # noqa: S112 continue except Exception: return None return None def _pyproject_via_dist_files(dist: importlib.metadata.Distribution) -> Path | None: """Locate pyproject.toml by scanning the distribution's file list.""" package_name = _normalize_package_name(dist.name) files = getattr(dist, "files", None) if not files: return None for file in files: if getattr(file, "name", None) == "pyproject.toml" or str(file).endswith( "pyproject.toml" ): try: pyproject_path = Path(str(dist.locate_file(file))) if _validate_pyproject_for_package( pyproject_path, dist.name, package_name, ): return pyproject_path except Exception: # noqa: S112 continue return None def _pyproject_via_import_spec( dist: importlib.metadata.Distribution, package_name: str ) -> Path | None: """Locate pyproject.toml by resolving the import spec and checking nearby. For editable installs, try the package directory and its parent only. """ try: spec = importlib.util.find_spec(package_name) if spec and spec.origin: package_dir = Path(spec.origin).parent for search_dir in [package_dir, package_dir.parent]: pyproject_path = search_dir / "pyproject.toml" if pyproject_path.exists() and _validate_pyproject_for_package( pyproject_path, dist.name, package_name, ): return pyproject_path except Exception: return None return None def _validate_pyproject_for_package( pyproject_path: Path, dist_name: str, package_name: str ) -> bool: """Validate that a ``pyproject.toml`` file belongs to the specified package. Parameters ---------- pyproject_path : Path Path to the pyproject.toml file to validate. dist_name : str The distribution name (e.g., "streamlit-bokeh"). package_name : str The package name (e.g., "streamlit_bokeh"). Returns ------- bool True if the file belongs to this package, False otherwise. """ try: with open(pyproject_path, encoding="utf-8") as f: pyproject_data = toml.load(f) # Check if this pyproject.toml is for the package we're looking for project_name = None # Try to get the project name from [project] table if "project" in pyproject_data and "name" in pyproject_data["project"]: project_name = pyproject_data["project"]["name"] # Also try to get it from [tool.setuptools] or other build system configs if ( not project_name and "tool" in pyproject_data and ( "setuptools" in pyproject_data["tool"] and "package-name" in pyproject_data["tool"]["setuptools"] ) ): project_name = pyproject_data["tool"]["setuptools"]["package-name"] # If we found a project name, check if it matches either the dist name or package name if project_name: # Normalize names for comparison using PEP 503 canonicalization # This handles hyphens, underscores, and dots consistently. canonical_project = packaging_utils.canonicalize_name(project_name) canonical_dist = packaging_utils.canonicalize_name(dist_name) canonical_package = packaging_utils.canonicalize_name(package_name) # Check if project name matches either the distribution name or the package name return canonical_project in {canonical_dist, canonical_package} # If we can't determine ownership, be conservative and reject it return False except Exception as e: _LOGGER.debug( "Error validating pyproject.toml at %s for %s: %s", pyproject_path, dist_name, e, ) return False def _load_pyproject(pyproject_path: Path) -> dict[str, Any] | None: """Load and parse a pyproject.toml, returning parsed data or None on failure.""" try: with open(pyproject_path, encoding="utf-8") as f: return toml.load(f) except Exception as e: _LOGGER.debug("Failed to parse pyproject.toml at %s: %s", pyproject_path, e) return None def _extract_components(pyproject_data: dict[str, Any]) -> list[dict[str, Any]] | None: """Extract raw component dicts from pyproject data; return None if absent.""" streamlit_component = ( pyproject_data.get("tool", {}).get("streamlit", {}).get("component") ) if not streamlit_component: return None raw_components = streamlit_component.get("components") if not isinstance(raw_components, list): return None # Ensure a list of dicts for type safety result: list[dict[str, Any]] = [ item for item in raw_components if isinstance(item, dict) ] if not result: return None return result def _resolve_package_root( dist: importlib.metadata.Distribution, package_name: str, pyproject_path: Path ) -> Path: """Resolve the package root directory with fallbacks.""" package_root: Path | None = None try: spec = importlib.util.find_spec(package_name) if spec and spec.origin: package_root = Path(spec.origin).parent except Exception as e: _LOGGER.debug( "Failed to resolve package root via import spec for %s: %s", package_name, e, ) files = getattr(dist, "files", None) if not package_root and files: for file in files: if package_name in str(file) and "__init__.py" in str(file): try: init_path = Path(str(dist.locate_file(file))) package_root = init_path.parent break except Exception as e: _LOGGER.debug( "Failed to resolve package root via dist files for %s: %s", package_name, e, ) if not package_root: package_root = pyproject_path.parent return package_root def _derive_project_metadata( pyproject_data: dict[str, Any], dist: importlib.metadata.Distribution ) -> tuple[str, str]: """Derive project name and version with safe fallbacks.""" project_table = pyproject_data.get("project", {}) derived_name = project_table.get("name") or dist.name derived_version = project_table.get("version") or dist.version or "0.0.0" return derived_name, derived_version def _process_single_package( dist: importlib.metadata.Distribution, ) -> tuple[ComponentManifest, Path] | None: """Process a single package to extract component manifest. This function is designed to be called from a thread pool for parallel processing. Parameters ---------- dist : importlib.metadata.Distribution The package distribution to process. Returns ------- tuple[ComponentManifest, Path] | None The manifest and package root if found, otherwise ``None``. """ try: pyproject_path = _find_package_pyproject_toml(dist) if not pyproject_path: return None pyproject_data = _load_pyproject(pyproject_path) if pyproject_data is None: return None raw_components = _extract_components(pyproject_data) if not raw_components: return None package_name = _normalize_package_name(dist.name) package_root = _resolve_package_root(dist, package_name, pyproject_path) derived_name, derived_version = _derive_project_metadata(pyproject_data, dist) parsed_components: list[ComponentConfig] = [ parsed for comp in raw_components if (parsed := ComponentConfig.parse_or_none(comp)) is not None ] if not parsed_components: return None manifest = ComponentManifest( name=derived_name, version=derived_version, components=parsed_components, ) return (manifest, package_root) except Exception as e: _LOGGER.debug( "Unexpected error processing distribution %s: %s", getattr(dist, "name", "<unknown>"), e, ) return None def scan_component_manifests( max_workers: int | None = None, ) -> list[tuple[ComponentManifest, Path]]: """Scan installed packages for Streamlit component metadata. Uses parallel processing to improve performance in environments with many installed packages. Applies early filtering to only check packages likely to contain streamlit components. Parameters ---------- max_workers : int or None Maximum number of worker threads. If None, uses min(32, (os.cpu_count() or 1) + 4). Returns ------- list[tuple[ComponentManifest, Path]] List of tuples of manifests and their package root paths. """ manifests: list[tuple[ComponentManifest, Path]] = [] # Get all distributions first (this is fast) all_distributions = list(importlib.metadata.distributions()) if not all_distributions: return manifests # Apply early filtering to reduce expensive file operations candidate_distributions = [ dist for dist in all_distributions if _is_likely_streamlit_component_package(dist) ] _LOGGER.debug( "Filtered %d packages down to %d candidates for component scanning", len(all_distributions), len(candidate_distributions), ) if not candidate_distributions: return manifests # Default max_workers follows ThreadPoolExecutor's default logic if max_workers is None: max_workers = min(32, (os.cpu_count() or 1) + 4) # Clamp max_workers to reasonable bounds for this task max_workers = min( max_workers, len(candidate_distributions), 16 ) # Don't use more threads than packages or 16 _LOGGER.debug( "Scanning %d candidate packages for component manifests using %d worker threads", len(candidate_distributions), max_workers, ) # Process packages in parallel with ThreadPoolExecutor(max_workers=max_workers) as executor: # Submit all tasks future_to_dist = { executor.submit(_process_single_package, dist): dist.name for dist in candidate_distributions } # Collect results as they complete for future in as_completed(future_to_dist): result = future.result() if result: manifests.append(result) _LOGGER.debug("Found %d component manifests total", len(manifests)) return manifests
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/components/v2/manifest_scanner.py", "license": "Apache License 2.0", "lines": 508, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_manifest_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import tempfile from pathlib import Path import pytest from streamlit.components.v2.component_manifest_handler import ( ComponentManifestHandler, ) from streamlit.components.v2.manifest_scanner import ComponentConfig, ComponentManifest from streamlit.errors import StreamlitComponentRegistryError def test_component_manifest_handler_stores_asset_dir() -> None: """Test that ComponentManifestHandler parses and persists asset_dir per component.""" # Create a manifest with an asset_dir entry manifest = ComponentManifest( name="test-package", version="1.0.0", components=[ComponentConfig(name="slider", asset_dir="slider/assets")], ) handler = ComponentManifestHandler() # Create a real temp package root and asset_dir to satisfy existence check with tempfile.TemporaryDirectory() as temp_dir: package_root = Path(temp_dir) os.makedirs(package_root / "slider" / "assets") handler.process_manifest(manifest, package_root) # Fully qualified name comp_full_name = "test-package.slider" asset_root = handler.get_asset_root(comp_full_name) assert asset_root is not None assert asset_root == (package_root / "slider/assets").resolve() def test_component_manifest_handler_get_asset_root_none_when_missing() -> None: """Test that get_asset_root returns None when asset_dir is not provided.""" manifest = ComponentManifest( name="test-package", version="1.0.0", components=[ComponentConfig(name="slider")], ) handler = ComponentManifestHandler() package_root = Path("/pkg/root") handler.process_manifest(manifest, package_root) comp_full_name = "test-package.slider" assert handler.get_asset_root(comp_full_name) is None @pytest.mark.skipif(not hasattr(os, "symlink"), reason="OS does not support symlinks") def test_component_manifest_handler_rejects_asset_dir_symlink_outside_root() -> None: """asset_dir that resolves outside package_root via symlink must be rejected.""" manifest = ComponentManifest( name="test-package", version="1.0.0", components=[ComponentConfig(name="widget", asset_dir="linked_outside")], ) handler = ComponentManifestHandler() with tempfile.TemporaryDirectory() as temp_dir: package_root = Path(temp_dir) / "pkg" outside_root = Path(temp_dir) / "outside" real_outside_assets = outside_root / "assets" real_outside_assets.mkdir(parents=True, exist_ok=True) link_inside = package_root / "linked_outside" link_inside.parent.mkdir(parents=True, exist_ok=True) try: os.symlink( str(real_outside_assets), str(link_inside), target_is_directory=True ) except (OSError, NotImplementedError): pytest.skip("Symlink creation not permitted in this environment") with pytest.raises(StreamlitComponentRegistryError): handler.process_manifest(manifest, package_root) @pytest.mark.skipif(not hasattr(os, "symlink"), reason="OS does not support symlinks") def test_component_manifest_handler_allows_symlink_within_root() -> None: """asset_dir symlinked within package_root should be accepted and resolved.""" manifest = ComponentManifest( name="test-package", version="1.0.0", components=[ComponentConfig(name="widget", asset_dir="linked_inside")], ) handler = ComponentManifestHandler() with tempfile.TemporaryDirectory() as temp_dir: package_root = Path(temp_dir) / "pkg" real_assets = package_root / "real_assets" real_assets.mkdir(parents=True, exist_ok=True) link_inside = package_root / "linked_inside" try: os.symlink(str(real_assets), str(link_inside), target_is_directory=True) except (OSError, NotImplementedError): pytest.skip("Symlink creation not permitted in this environment") handler.process_manifest(manifest, package_root) comp_full_name = "test-package.widget" asset_root = handler.get_asset_root(comp_full_name) assert asset_root == real_assets.resolve()
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_component_manifest_handler.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_path_utils.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os from typing import TYPE_CHECKING import pytest from streamlit.components.v2.component_path_utils import ComponentPathUtils from streamlit.errors import StreamlitComponentRegistryError if TYPE_CHECKING: from pathlib import Path def _touch(path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text("console.log('ok');", encoding="utf-8") def test_resolve_glob_pattern_accepts_file_within_root(tmp_path: Path) -> None: """Resolves a simple relative path within the package root.""" package_root = tmp_path / "pkg" asset = package_root / "assets" / "main.js" _touch(asset) resolved = ComponentPathUtils.resolve_glob_pattern( pattern="assets/main.js", package_root=package_root ) assert resolved == asset.resolve() def test_resolve_glob_pattern_handles_subdirectory_wildcards_single_match( tmp_path: Path, ) -> None: """Resolves a wildcard pattern when only one match exists.""" package_root = tmp_path / "pkg" a1 = package_root / "assets" / "v1" / "main.js" a2 = package_root / "assets" / "v2" / "other.js" _touch(a1) _touch(a2) # Only one file should match this pattern resolved = ComponentPathUtils.resolve_glob_pattern( pattern="assets/*/main.js", package_root=package_root ) assert resolved == a1.resolve() def test_resolve_glob_pattern_raises_on_multiple_matches(tmp_path: Path) -> None: """Raises when wildcard pattern matches multiple files.""" package_root = tmp_path / "pkg" a1 = package_root / "assets" / "v1" / "main.js" a2 = package_root / "assets" / "v2" / "main.js" _touch(a1) _touch(a2) with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern( pattern="assets/*/main.js", package_root=package_root ) def test_ensure_within_root_blocks_outside_with_prefix_collision( tmp_path: Path, ) -> None: """Blocks files outside root even if paths share a prefix.""" root = tmp_path / "package" inside_file = root / "dir" / "file.js" outside_file = tmp_path / "package_malicious" / "file.js" _touch(inside_file) _touch(outside_file) # Sanity: inside should not raise ComponentPathUtils.ensure_within_root( abs_path=inside_file.resolve(), root=root.resolve(), kind="js" ) # Prevent a prefix-collision path escape: an attacker could place files in a # sibling directory named "package_malicious" that shares the "package" # prefix to bypass naive prefix-based checks and access files outside the # package root. Such access must raise. with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.ensure_within_root( abs_path=outside_file.resolve(), root=root.resolve(), kind="js" ) @pytest.mark.skipif(not hasattr(os, "symlink"), reason="OS does not support symlinks") def test_resolve_glob_pattern_rejects_symlink_pointing_outside_root( tmp_path: Path, ) -> None: """Rejects symlinked files that resolve outside the package root.""" package_root = tmp_path / "pkg" outside_dir = tmp_path / "outside" outside_file = outside_dir / "evil.js" _touch(outside_file) link_dir = package_root / "link" link_dir.parent.mkdir(parents=True, exist_ok=True) try: os.symlink(str(outside_dir), str(link_dir), target_is_directory=True) except (OSError, NotImplementedError): pytest.skip("Symlink creation not permitted in this environment") # The pattern targets a file reachable via a symlink inside package_root, # but the resolved path points outside. It must be ignored, causing a # 'no files found' error. with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern( pattern="link/evil.js", package_root=package_root ) @pytest.mark.parametrize( "invalid_path", [ "/etc/passwd", # POSIX absolute "C:\\Windows\\system32", # Windows drive "\\\\server\\share\\file", # UNC "../secret", # traversal "dir/../secret", # traversal in middle "\\rooted\\path", # rooted backslash "C:\\mix/sep\\file.js", # mixed separators but absolute ], ) def test_validate_path_security_rejects_invalid_paths(invalid_path: str) -> None: """Absolute, rooted-backslash, and traversal paths must be rejected.""" with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.validate_path_security(invalid_path) def test_validate_path_security_allows_non_traversal_double_dots() -> None: """Double dots in filenames are allowed when not a traversal segment.""" # Should not raise ComponentPathUtils.validate_path_security("dir/file..js") @pytest.mark.parametrize( "invalid_pattern", [ "/etc/*.js", # POSIX absolute "C:/Windows/*.dll", # Windows drive "\\\\server\\share\\*.js", # UNC "../assets/*.js", # traversal "assets/../*.js", # traversal in middle "\\assets\\*.js", # rooted backslash "assets/**/../evil.js", # traversal with glob ], ) def test_resolve_glob_pattern_rejects_invalid_patterns( tmp_path: Path, invalid_pattern: str ) -> None: """resolve_glob_pattern must reject absolute, rooted-backslash, and traversal patterns.""" package_root = tmp_path / "pkg" (package_root / "assets").mkdir(parents=True, exist_ok=True) with pytest.raises(StreamlitComponentRegistryError): ComponentPathUtils.resolve_glob_pattern( pattern=invalid_pattern, package_root=package_root ) def test_validate_path_security_allows_current_dir_segment() -> None: """'.' segments are benign and should not raise.""" ComponentPathUtils.validate_path_security("./assets/file.js") ComponentPathUtils.validate_path_security("assets/./file.js") def test_resolve_glob_pattern_accepts_dot_prefixed_relative(tmp_path: Path) -> None: """'./' prefixed relative patterns should resolve normally within root.""" package_root = tmp_path / "pkg" asset = package_root / "assets" / "a.js" asset.parent.mkdir(parents=True, exist_ok=True) asset.write_text("console.log('ok');", encoding="utf-8") resolved = ComponentPathUtils.resolve_glob_pattern( pattern="./assets/a.js", package_root=package_root ) assert resolved == asset.resolve() @pytest.mark.parametrize( ("value", "expected_inline"), [ ("console.log('x')", True), # Base JS case -> inline ("console.log('x')\nalert('y')", True), # newlines -> inline ("var x = 1;/*no path*/", False), # has '/' -> path-like ("var x = 1;\n/*no path*/", True), # multiline -> inline ("assets/main.js", False), ("./main.css", False), ("dir\\file.mjs", False), ("file.cjs", False), ], ) def test_looks_like_inline_content_heuristic(value: str, expected_inline: bool) -> None: """Inline content heuristic should classify strings correctly across cases.""" assert ComponentPathUtils.looks_like_inline_content(value) == expected_inline
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_component_path_utils.py", "license": "Apache License 2.0", "lines": 173, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/components/v2/test_manifest_scanner.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import tempfile from pathlib import Path from unittest.mock import MagicMock, Mock, mock_open, patch from parameterized import parameterized from streamlit.components.v2.manifest_scanner import ComponentConfig, ComponentManifest @parameterized.expand( [ ("hyphen_to_underscore", "my-awesome-component", "my_awesome_component"), ("no_change_simple", "simple", "simple"), ( "already_normalized", "already_normalized_name", "already_normalized_name", ), ( "preserve_dots_and_case", "Streamlit.Bokeh", "Streamlit.Bokeh", ), ("hyphen_replaced_before_dot", "foo-bar.baz", "foo_bar.baz"), ] ) def test_normalize_package_name_param(_case: str, raw: str, expected: str) -> None: """Validate name normalization across representative cases.""" from streamlit.components.v2.manifest_scanner import _normalize_package_name assert _normalize_package_name(raw) == expected def test_process_single_package_no_files() -> None: """Test _process_single_package with distribution that has no files.""" from streamlit.components.v2.manifest_scanner import _process_single_package # Create mock distribution with no files mock_dist = Mock() mock_dist.files = None mock_dist.name = "test-package" result = _process_single_package(mock_dist) assert result is None def test_process_single_package_no_pyproject() -> None: """Test _process_single_package with distribution that has no pyproject.toml.""" from streamlit.components.v2.manifest_scanner import _process_single_package # Create mock distribution with files but no pyproject.toml mock_file = Mock() mock_file.name = "some_file.py" mock_dist = Mock() mock_dist.files = [mock_file] mock_dist.name = "test-package" result = _process_single_package(mock_dist) assert result is None def test_process_single_package_no_streamlit_config() -> None: """Test _process_single_package with pyproject.toml but no Streamlit config.""" from streamlit.components.v2.manifest_scanner import _process_single_package # Create mock file and distribution mock_file = Mock() mock_file.name = "pyproject.toml" mock_dist = Mock() mock_dist.files = [mock_file] mock_dist.name = "test-package" mock_dist.locate_file.return_value = "/path/to/pyproject.toml" # Mock toml content without Streamlit config toml_content = """ [build-system] requires = ["setuptools"] [project] name = "test-package" """ with ( patch("builtins.open", mock_open(read_data=toml_content)), patch("streamlit.components.v2.manifest_scanner.toml.load") as mock_toml_load, patch("streamlit.components.v2.manifest_scanner.Path"), ): mock_toml_load.return_value = { "build-system": {"requires": ["setuptools"]}, "project": {"name": "test-package"}, } result = _process_single_package(mock_dist) assert result is None def test_process_single_package_valid_manifest() -> None: """Test _process_single_package with valid Streamlit component manifest.""" from streamlit.components.v2.manifest_scanner import _process_single_package # Create mock file and distribution mock_file = Mock() mock_file.name = "pyproject.toml" mock_init_file = Mock() mock_init_file.__str__ = Mock(return_value="test_package/__init__.py") mock_dist = Mock() mock_dist.files = [mock_file, mock_init_file] mock_dist.name = "test-package" mock_dist.locate_file.side_effect = lambda f: ( "/path/to/pyproject.toml" if f == mock_file else "/path/to/test_package/__init__.py" ) with ( patch("builtins.open", mock_open()), patch("streamlit.components.v2.manifest_scanner.toml.load") as mock_toml_load, patch("streamlit.components.v2.manifest_scanner.Path") as mock_path, ): mock_toml_load.return_value = { "project": {"name": "test-package", "version": "1.0.0"}, "tool": { "streamlit": { "component": { "components": [ { "name": "slider", "js": "slider.js", "css": "slider.css", } ], } } }, } # Mock Path behavior mock_path_instance = Mock() mock_path_instance.parent = "/path/to/test_package" mock_path.return_value = mock_path_instance result = _process_single_package(mock_dist) assert result is not None manifest, _package_root = result assert manifest.name == "test-package" assert manifest.version == "1.0.0" assert len(manifest.components) == 1 assert manifest.components[0].name == "slider" def test_scan_multiple_component_manifests() -> None: """Test that scanning handles multiple packages correctly.""" from streamlit.components.v2.manifest_scanner import ( scan_component_manifests, ) # Create mock distributions with proper name and metadata attributes mock_dists = [] for i in range(10): mock_dist = Mock() # Make some packages look like streamlit components if i < 5: mock_dist.name = f"streamlit-package-{i}" package_name = f"streamlit-package-{i}" else: mock_dist.name = f"package-{i}" package_name = f"package-{i}" # Mock metadata that returns proper strings mock_metadata = MagicMock() metadata_dict = { "Name": package_name, "Summary": f"Description for {package_name}", } mock_metadata.__getitem__.side_effect = metadata_dict.__getitem__ mock_metadata.__contains__.side_effect = metadata_dict.__contains__ mock_metadata.get_all.return_value = [] mock_dist.metadata = mock_metadata mock_dists.append(mock_dist) results = [] for i in range(3): # Only 3 packages have valid manifests results.append( ( ComponentManifest( name=f"component_{i}", version="1.0.0", components=[ComponentConfig(name="test")], ), Path(f"/path/to/component_{i}"), ) ) with ( patch( "streamlit.components.v2.manifest_scanner.importlib.metadata.distributions" ) as mock_distributions, patch( "streamlit.components.v2.manifest_scanner._process_single_package" ) as mock_process, ): mock_distributions.return_value = mock_dists mock_process.side_effect = lambda dist: ( results[int(dist.name.split("-")[-1])] if "streamlit" in dist.name and int(dist.name.split("-")[-1]) < 3 else None ) manifests = scan_component_manifests(max_workers=2) # Should return 3 valid manifests assert len(manifests) == 3 assert all(manifest.name.startswith("component_") for manifest, _ in manifests) def test_scan_component_manifests_max_workers() -> None: """Test that max_workers parameter is respected.""" from streamlit.components.v2.manifest_scanner import ( scan_component_manifests, ) # Create a small number of mock distributions with proper name and metadata attributes mock_dists = [] for i in range(3): mock_dist = Mock() # Make all packages look like streamlit components for this test mock_dist.name = f"streamlit-package-{i}" package_name = f"streamlit-package-{i}" # Mock metadata that returns proper strings mock_metadata = MagicMock() metadata_dict = { "Name": package_name, "Summary": f"Description for {package_name}", } mock_metadata.__getitem__.side_effect = metadata_dict.__getitem__ mock_metadata.__contains__.side_effect = metadata_dict.__contains__ mock_metadata.get_all.return_value = [] mock_dist.metadata = mock_metadata mock_dists.append(mock_dist) with ( patch( "streamlit.components.v2.manifest_scanner.importlib.metadata.distributions" ) as mock_distributions, patch( "streamlit.components.v2.manifest_scanner._process_single_package" ) as mock_process, patch( "streamlit.components.v2.manifest_scanner.ThreadPoolExecutor" ) as mock_executor, ): mock_distributions.return_value = mock_dists mock_process.return_value = None # Mock the executor to work with as_completed mock_executor_instance = Mock() mock_executor.return_value.__enter__.return_value = mock_executor_instance mock_future = Mock() mock_future.result.return_value = None mock_executor_instance.submit.return_value = mock_future # Mock as_completed to return the futures immediately with patch( "streamlit.components.v2.manifest_scanner.as_completed" ) as mock_as_completed: mock_as_completed.return_value = [mock_future] * len(mock_dists) # Test with explicit max_workers scan_component_manifests(max_workers=2) mock_executor.assert_called_with(max_workers=2) # Test with default max_workers (should be limited by number of packages) scan_component_manifests() # Should use min(default, len(distributions), 16) = min(?, 3, 16) = 3 assert mock_executor.call_args[1]["max_workers"] <= 3 def test_scan_component_manifests_empty_distributions() -> None: """Test scanning with no installed packages.""" from streamlit.components.v2.manifest_scanner import ( scan_component_manifests, ) with patch( "streamlit.components.v2.manifest_scanner.importlib.metadata.distributions" ) as mock_distributions: mock_distributions.return_value = [] manifests = scan_component_manifests() assert manifests == [] @parameterized.expand( [ ("none_name", None), ("empty_string_name", ""), ] ) def test_scan_component_manifests_skips_distributions_without_name( _case: str, dist_name: str | None ) -> None: """Test scanning skips distributions with missing or invalid dist.name.""" from streamlit.components.v2.manifest_scanner import scan_component_manifests invalid_dist = Mock() invalid_dist.name = dist_name invalid_metadata = MagicMock() invalid_metadata.__contains__.return_value = False invalid_metadata.get_all.return_value = [] invalid_dist.metadata = invalid_metadata valid_dist = Mock() valid_dist.name = "streamlit-package-0" valid_metadata = MagicMock() metadata_dict = { "Name": "streamlit-package-0", "Summary": "Description for streamlit-package-0", } valid_metadata.__getitem__.side_effect = metadata_dict.__getitem__ valid_metadata.__contains__.side_effect = metadata_dict.__contains__ valid_metadata.get_all.return_value = [] valid_dist.metadata = valid_metadata with ( patch( "streamlit.components.v2.manifest_scanner.importlib.metadata.distributions" ) as mock_distributions, patch( "streamlit.components.v2.manifest_scanner._process_single_package" ) as mock_process, ): mock_distributions.return_value = [invalid_dist, valid_dist] mock_process.return_value = None # Should not raise, even with malformed distributions. manifests = scan_component_manifests(max_workers=1) assert manifests == [] # Anti-regression: do not attempt to process the invalid distribution. mock_process.assert_called_once_with(valid_dist) def test_scan_component_manifests_error_handling() -> None: """Test that scanning handles errors gracefully.""" from streamlit.components.v2.manifest_scanner import ( scan_component_manifests, ) # Create mock distributions, some will cause errors mock_dists = [] for i in range(5): mock_dist = Mock() # Make all packages look like streamlit components for this test mock_dist.name = f"streamlit-package-{i}" package_name = f"streamlit-package-{i}" # Mock metadata that returns proper strings mock_metadata = MagicMock() metadata_dict = { "Name": package_name, "Summary": f"Description for {package_name}", } mock_metadata.__getitem__.side_effect = metadata_dict.__getitem__ mock_metadata.__contains__.side_effect = metadata_dict.__contains__ mock_metadata.get_all.return_value = [] mock_dist.metadata = mock_metadata mock_dists.append(mock_dist) def mock_process_with_errors(dist): if "package-2" in dist.name: # Simulate an error by returning None (what the real function does on error) return return # For this test, all packages return None (no manifests found) with ( patch( "streamlit.components.v2.manifest_scanner.importlib.metadata.distributions" ) as mock_distributions, patch( "streamlit.components.v2.manifest_scanner._process_single_package" ) as mock_process, ): mock_distributions.return_value = mock_dists mock_process.side_effect = mock_process_with_errors # Should not raise exception even with errors manifests = scan_component_manifests() assert manifests == [] # Tests for editable installs and _find_package_pyproject_toml function @parameterized.expand( [ ( "project_name_match", '[project]\nname = "test-package"\n', ( ("test-package", "test_package", True), ("test_package", "test_package", True), ("different-package", "different_package", False), ), ), ( "requires_explicit_project_name", "[tool.streamlit.component]\ncomponents = []\n", (("test-package", "test_package", False),), ), ( "no_match_other_tool", '[project]\nname = "different-package"\n\n[tool.other]\nconfig = "value"\n', (("test-package", "test_package", False),), ), ( "invalid_file", "invalid toml content [[[", (("test-package", "test_package", False),), ), ( "uses_package_name", '[project]\nname = "my_component"\n', ( ("my-awesome-component", "my_component", True), ("different-component", "different_component", False), ), ), ( "canonicalization_cases_streamlit_bokeh", '[project]\nname = "Streamlit.Bokeh"\n', (("streamlit-bokeh", "streamlit_bokeh", True),), ), ( "canonicalization_cases_mixed_separators", '[project]\nname = "foo_-bar"\n', (("foo-bar", "foo_bar", True),), ), ( "canonicalization_cases_upper_and_multiple", '[project]\nname = "FOO...BAR__BAZ"\n', (("foo-bar-baz", "foo_bar_baz", True),), ), ( "canonicalization_negative", '[project]\nname = "streamlit.bokeh"\n', (("streamlit-other", "streamlit_other", False),), ), ] ) def test_validate_pyproject_for_package_param( _case: str, pyproject_text: str, checks: tuple[tuple[str, str, bool], ...] ) -> None: """Validate pyproject parsing and name matching across many scenarios.""" from streamlit.components.v2.manifest_scanner import _validate_pyproject_for_package with tempfile.TemporaryDirectory() as temp_dir: pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text(pyproject_text.strip()) for dist_name, package_name, expected in checks: assert ( _validate_pyproject_for_package(pyproject_path, dist_name, package_name) is expected ) def test_find_package_pyproject_toml_traditional_approach() -> None: """Test _find_package_pyproject_toml with traditional dist.files approach.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml # Create mock file and distribution mock_file = Mock() mock_file.name = "pyproject.toml" mock_dist = Mock() mock_dist.files = [mock_file] mock_dist.name = "test-package" mock_dist.locate_file.return_value = "/path/to/pyproject.toml" # Make sure read_text fails so it goes to the traditional approach mock_dist.read_text.side_effect = Exception("read_text not available") with ( patch("streamlit.components.v2.manifest_scanner.Path") as mock_path_class, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, ): # Create a real Path object that the function can use expected_path = Path("/path/to/pyproject.toml") mock_path_class.return_value = expected_path mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) assert result == expected_path mock_dist.locate_file.assert_called_once_with(mock_file) mock_validate.assert_called_once_with( expected_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_traditional_approach_fails() -> None: """Test _find_package_pyproject_toml when traditional approach fails but file exists.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml # Create mock file and distribution mock_file = Mock() mock_file.name = "pyproject.toml" mock_dist = Mock() mock_dist.files = [mock_file] mock_dist.name = "test-package" mock_dist.locate_file.side_effect = Exception("Failed to locate file") with ( patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): # Create package directory package_dir = Path(temp_dir) / "test_package" package_dir.mkdir() # Mock importlib to find the package mock_spec = Mock() mock_spec.origin = str(package_dir / "__init__.py") mock_find_spec.return_value = mock_spec # Create pyproject.toml file in the package directory pyproject_path = package_dir / "pyproject.toml" pyproject_path.write_text("[project]\nname = 'test-package'") # Mock validation to return True mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) assert result == pyproject_path mock_find_spec.assert_called_once_with("test_package") mock_validate.assert_called_once_with( pyproject_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_editable_install() -> None: """Test _find_package_pyproject_toml with editable install (no dist.files).""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml mock_dist = Mock() mock_dist.files = None # Simulates editable install mock_dist.name = "test-package" with ( patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): # Create a real directory structure for testing package_dir = Path(temp_dir) / "test_package" package_dir.mkdir() pyproject_path = package_dir / "pyproject.toml" pyproject_path.write_text("[project]\nname = 'test-package'") # Mock importlib to find the package mock_spec = Mock() mock_spec.origin = str(package_dir / "__init__.py") mock_find_spec.return_value = mock_spec # Mock validation to return True mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) assert result == pyproject_path mock_find_spec.assert_called_once_with("test_package") mock_validate.assert_called_once_with( pyproject_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_no_parent_traversal() -> None: """Test _find_package_pyproject_toml does not traverse parent directories for security.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml mock_dist = Mock() mock_dist.files = None mock_dist.name = "test-package" with ( patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): # Create a nested directory structure src_dir = Path(temp_dir) / "src" src_dir.mkdir() package_dir = src_dir / "test_package" package_dir.mkdir() # Create pyproject.toml in the root directory (parent of src/) pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text("[project]\nname = 'test-package'") # Mock importlib to find the package mock_spec = Mock() mock_spec.origin = str(package_dir / "__init__.py") mock_find_spec.return_value = mock_spec # Mock validation to return True mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) # For security, should NOT find pyproject.toml in parent directory assert result is None mock_find_spec.assert_called_once_with("test_package") # Should check package directory but not find pyproject.toml there mock_validate.assert_not_called() def test_find_package_pyproject_toml_read_text_approach() -> None: """Test _find_package_pyproject_toml using dist.read_text() method for editable installs.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml # Create a mock file that looks like a Python file mock_file = Mock() mock_file.name = ( "__init__.py" # This will match the condition in the implementation ) mock_file.__str__ = Mock(return_value="__init__.py") # Make sure str(file) works mock_dist = Mock() mock_dist.files = [mock_file] mock_dist.name = "test-package" mock_dist.read_text.return_value = "[project]\nname = 'test-package'" with ( patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): # Create a real pyproject.toml file that validation can find pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text("[project]\nname = 'test-package'") # Mock locate_file to return a file in the same directory as pyproject.toml mock_dist.locate_file.return_value = Path(temp_dir) / "__init__.py" # Mock validation to return True mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) assert result == pyproject_path mock_dist.read_text.assert_called_once_with("pyproject.toml") mock_validate.assert_called_once_with( pyproject_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_path_distribution() -> None: """Test _find_package_pyproject_toml using Method 3 (find_spec) for editable installs.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml mock_dist = Mock() mock_dist.files = None # No files to trigger Methods 1 and 2 failure mock_dist.name = "test-package" # Make sure read_text fails so it doesn't use Method 1 mock_dist.read_text.side_effect = Exception("read_text not available") with ( patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): # Create pyproject.toml in temp directory pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text("[project]\nname = 'test-package'") # Mock find_spec to return a spec that points to our temp directory mock_spec = Mock() mock_spec.origin = str(Path(temp_dir) / "__init__.py") mock_find_spec.return_value = mock_spec # Mock validation to return True mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) assert result == pyproject_path mock_validate.assert_called_once_with( pyproject_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_validation_rejects_wrong_package() -> None: """Test _find_package_pyproject_toml when validation rejects wrong package.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml mock_dist = Mock() mock_dist.files = None mock_dist.name = "test-package" with ( patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): # Create directory structure package_dir = Path(temp_dir) / "test_package" package_dir.mkdir() pyproject_path = package_dir / "pyproject.toml" pyproject_path.write_text( "[project]\nname = 'different-package'" ) # Wrong package # Mock importlib to find the package mock_spec = Mock() mock_spec.origin = str(package_dir / "__init__.py") mock_find_spec.return_value = mock_spec # Mock validation to return False (wrong package) mock_validate.return_value = False result = _find_package_pyproject_toml(mock_dist) assert result is None # Should not find anything mock_validate.assert_called_once_with( pyproject_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_read_text_fallback() -> None: """Test _find_package_pyproject_toml using read_text fallback method.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml mock_dist = Mock() mock_dist.name = "test-package" mock_dist.read_text.return_value = "[project]\nname = 'test-package'" # Mock importlib to fail with ( patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch( "streamlit.components.v2.manifest_scanner._validate_pyproject_for_package" ) as mock_validate, tempfile.TemporaryDirectory() as temp_dir, ): mock_find_spec.side_effect = Exception("Package not found") # Create some files to work with package_dir = Path(temp_dir) / "test_package" package_dir.mkdir() pyproject_path = package_dir / "pyproject.toml" pyproject_path.write_text("[project]\nname = 'test-package'") # Create a mock file that looks like a Python file mock_file = Mock() mock_file.name = "some_file.py" mock_file.__str__ = Mock(return_value="some_file.py") mock_dist.files = [mock_file] mock_dist.locate_file.return_value = str(package_dir / "some_file.py") # Mock validation to return True mock_validate.return_value = True result = _find_package_pyproject_toml(mock_dist) assert result == pyproject_path mock_dist.read_text.assert_called_once_with("pyproject.toml") mock_validate.assert_called_once_with( pyproject_path, "test-package", "test_package" ) def test_find_package_pyproject_toml_not_found() -> None: """Test _find_package_pyproject_toml when pyproject.toml cannot be found.""" from streamlit.components.v2.manifest_scanner import _find_package_pyproject_toml mock_dist = Mock() mock_dist.files = None mock_dist.name = "test-package" # Mock importlib to fail with patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec: mock_find_spec.side_effect = Exception("Package not found") result = _find_package_pyproject_toml(mock_dist) assert result is None def test_process_single_package_editable_install_success() -> None: """Test _process_single_package with successful editable install detection.""" from streamlit.components.v2.manifest_scanner import _process_single_package mock_dist = Mock() mock_dist.files = None # Editable install mock_dist.name = "my-awesome-component" pyproject_content = { "project": {"name": "my-awesome-component", "version": "2.0.0"}, "tool": { "streamlit": { "component": { "components": [ { "name": "slider", "js": "slider.js", "css": "slider.css", } ], } } }, } with ( patch( "streamlit.components.v2.manifest_scanner._find_package_pyproject_toml" ) as mock_find_pyproject, patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch("builtins.open", mock_open()), patch("streamlit.components.v2.manifest_scanner.toml.load") as mock_toml_load, tempfile.TemporaryDirectory() as temp_dir, ): # Create real directories for testing package_dir = Path(temp_dir) / "my_awesome_component" package_dir.mkdir() pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text("dummy content") # Mock the functions mock_find_pyproject.return_value = pyproject_path mock_toml_load.return_value = pyproject_content mock_spec = Mock() mock_spec.origin = str(package_dir / "__init__.py") mock_find_spec.return_value = mock_spec result = _process_single_package(mock_dist) assert result is not None manifest, package_root = result assert manifest.name == "my-awesome-component" assert manifest.version == "2.0.0" assert len(manifest.components) == 1 assert manifest.components[0].name == "slider" assert package_root == package_dir def test_process_single_package_editable_install_fallback_to_pyproject_parent() -> None: """Test _process_single_package falls back to pyproject.toml parent for package root.""" from streamlit.components.v2.manifest_scanner import _process_single_package mock_dist = Mock() mock_dist.files = None mock_dist.name = "test-component" pyproject_content = { "project": {"name": "test-component", "version": "1.0.0"}, "tool": { "streamlit": { "component": { "components": [{"name": "widget"}], } } }, } with ( patch( "streamlit.components.v2.manifest_scanner._find_package_pyproject_toml" ) as mock_find_pyproject, patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch("builtins.open", mock_open()), patch("streamlit.components.v2.manifest_scanner.toml.load") as mock_toml_load, tempfile.TemporaryDirectory() as temp_dir, ): # Create pyproject.toml in temp directory pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text("dummy content") # Mock functions mock_find_pyproject.return_value = pyproject_path mock_toml_load.return_value = pyproject_content # Mock importlib to fail finding the package (for both calls) mock_find_spec.side_effect = Exception("Package not found") result = _process_single_package(mock_dist) assert result is not None manifest, package_root = result assert manifest.name == "test-component" assert package_root == Path(temp_dir) # Should be pyproject.toml parent def test_process_single_package_mixed_install_scenarios() -> None: """Test _process_single_package handles mixed scenarios correctly.""" from streamlit.components.v2.manifest_scanner import _process_single_package mock_dist = Mock() mock_dist.files = None mock_dist.name = "mixed-component" pyproject_content = { "project": {"name": "mixed-component", "version": "1.5.0"}, "tool": { "streamlit": { "component": { "components": [{"name": "chart"}], } } }, } with ( patch( "streamlit.components.v2.manifest_scanner._find_package_pyproject_toml" ) as mock_find_pyproject, patch( "streamlit.components.v2.manifest_scanner.importlib.util.find_spec" ) as mock_find_spec, patch("builtins.open", mock_open()), patch("streamlit.components.v2.manifest_scanner.toml.load") as mock_toml_load, tempfile.TemporaryDirectory() as temp_dir, ): # Create real directories for testing package_dir = Path(temp_dir) / "mixed_component" package_dir.mkdir() pyproject_path = Path(temp_dir) / "pyproject.toml" pyproject_path.write_text("dummy content") # Mock functions mock_find_pyproject.return_value = pyproject_path mock_toml_load.return_value = pyproject_content mock_spec = Mock() mock_spec.origin = str(package_dir / "__init__.py") mock_find_spec.return_value = mock_spec result = _process_single_package(mock_dist) assert result is not None manifest, package_root = result assert manifest.name == "mixed-component" assert manifest.version == "1.5.0" assert package_root == package_dir
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/components/v2/test_manifest_scanner.py", "license": "Apache License 2.0", "lines": 825, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_dark_sidebar_theme.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import theme_tester_app # type: ignore theme_tester_app.run_theme_tester_app()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_dark_sidebar_theme.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/custom_dark_sidebar_theme_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ( ImageCompareFunction, build_app_url, wait_for_app_loaded, wait_for_app_run, ) from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture def app(page: Page, app_base_url: str) -> Page: """Custom app fixture that sets dark mode color scheme before navigation. This uses page.emulate_media() instead of browser_context_args to avoid conflicts with browser context lifecycle in Firefox. """ # Set dark mode color scheme before navigating to the app page.emulate_media(color_scheme="dark") response = page.goto(build_app_url(app_base_url, path="/")) if response is None or response.status != 200: raise RuntimeError("Unable to load page") wait_for_app_loaded(page) return page @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_dark_sidebar_theme(): """Configure custom dark sidebar theme.""" # [theme] configs os.environ["STREAMLIT_THEME_BASE"] = "dark" os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] = "14" os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] = "#004cbe" os.environ["STREAMLIT_THEME_TEXT_COLOR"] = "#bdc4d5" # [theme.dark] configs os.environ["STREAMLIT_THEME_DARK_BACKGROUND_COLOR"] = "#191e24" os.environ["STREAMLIT_THEME_DARK_SECONDARY_BACKGROUND_COLOR"] = "#0f161e" os.environ["STREAMLIT_THEME_DARK_BORDER_COLOR"] = "#293246" os.environ["STREAMLIT_THEME_DARK_FONT"] = ( "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, " "sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_DARK_HEADING_FONT"] = ( "bold Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, " "Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_DARK_CODE_FONT"] = ( '"Monaspace Argon", Menlo, Monaco, Consolas, "Courier New", monospace' ) # [theme.sidebar] configs os.environ["STREAMLIT_THEME_SIDEBAR_TEXT_COLOR"] = "#091c36" os.environ["STREAMLIT_THEME_SIDEBAR_BACKGROUND_COLOR"] = ( "#b4c3d6" # Should apply - override [theme.dark] config - light blue gray ) os.environ["STREAMLIT_THEME_SIDEBAR_SECONDARY_BACKGROUND_COLOR"] = ( "#c7cdd4" # Should apply - override [theme.dark] config - light gray ) os.environ["STREAMLIT_THEME_SIDEBAR_BORDER_COLOR"] = ( "#000000" # Overridden by [theme.dark.sidebar] config in dark theme ) os.environ["STREAMLIT_THEME_SIDEBAR_DATAFRAME_BORDER_COLOR"] = ( "#7851A9" # Should apply - new config option - royal purple ) # [theme.dark.sidebar] configs os.environ["STREAMLIT_THEME_DARK_SIDEBAR_BORDER_COLOR"] = ( "#ff6700" # hazard orange - should override [theme.dark] & [theme.sidebar] configs ) os.environ["STREAMLIT_THEME_DARK_SIDEBAR_LINK_COLOR"] = "#CD1C18" # chili red yield del os.environ["STREAMLIT_THEME_BASE"] del os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] del os.environ["STREAMLIT_THEME_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_DARK_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_DARK_SECONDARY_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_DARK_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_DARK_FONT"] del os.environ["STREAMLIT_THEME_DARK_HEADING_FONT"] del os.environ["STREAMLIT_THEME_DARK_CODE_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_SECONDARY_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_DATAFRAME_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_DARK_SIDEBAR_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_DARK_SIDEBAR_LINK_COLOR"] @pytest.mark.usefixtures("configure_custom_dark_sidebar_theme") def test_auto_sidebar_theme_with_dark_preference( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the auto sidebar theme is the Custom Theme Dark when the system preference is dark.""" # Browser preference should be light by default, updated to dark is_dark_mode = app.evaluate("matchMedia('(prefers-color-scheme: dark)').matches") assert is_dark_mode is True # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_dark_sidebar_theme_auto", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_dark_sidebar_theme") def test_custom_dark_sidebar_theme(app: Page, assert_snapshot: ImageCompareFunction): """Test that the custom dark sidebar theme is rendered correctly.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Change the theme to explicitly be Custom Dark Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Dark").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot(app, name="custom_dark_sidebar_theme", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_dark_sidebar_theme") def test_custom_light_sidebar_theme_with_no_light_configs( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the custom light sidebar theme is rendered correctly with no light configs.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Switch to Custom Light Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Light").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot( app, name="custom_light_sidebar_theme_no_light_configs", image_threshold=0.0003 )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_dark_sidebar_theme_test.py", "license": "Apache License 2.0", "lines": 138, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_dark_theme_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ( ImageCompareFunction, build_app_url, wait_for_app_loaded, wait_for_app_run, ) from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture def app(page: Page, app_base_url: str) -> Page: """Custom app fixture that sets dark mode color scheme before navigation. This uses page.emulate_media() instead of browser_context_args to avoid conflicts with browser context lifecycle in Firefox. """ # Set dark mode color scheme before navigating to the app page.emulate_media(color_scheme="dark") response = page.goto(build_app_url(app_base_url, path="/")) if response is None or response.status != 200: raise RuntimeError("Unable to load page") wait_for_app_loaded(page) return page @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_dark_theme(): """Configure custom dark theme.""" # [theme] configs os.environ["STREAMLIT_THEME_BASE"] = "dark" os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] = "#004cbe" os.environ["STREAMLIT_THEME_BACKGROUND_COLOR"] = "#191e24" os.environ["STREAMLIT_THEME_SECONDARY_BACKGROUND_COLOR"] = "#0f161e" os.environ["STREAMLIT_THEME_TEXT_COLOR"] = "#bdc4d5" os.environ["STREAMLIT_THEME_BORDER_COLOR"] = "#293246" os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] = "14" os.environ["STREAMLIT_THEME_FONT"] = ( "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, " "sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_HEADING_FONT"] = ( "bold Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, " "Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_CODE_FONT"] = ( '"Monaspace Argon", Menlo, Monaco, Consolas, "Courier New", monospace' ) # [theme.dark] configs os.environ["STREAMLIT_THEME_DARK_BORDER_COLOR"] = ( "#ff6700" # hazard orange - should override [theme] config above ) os.environ["STREAMLIT_THEME_DARK_CODE_FONT_SIZE"] = "13px" os.environ["STREAMLIT_THEME_DARK_CODE_TEXT_COLOR"] = "#d4c6f5" # lavender os.environ["STREAMLIT_THEME_DARK_LINK_COLOR"] = "#CD1C18" # chili red yield del os.environ["STREAMLIT_THEME_BASE"] del os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] del os.environ["STREAMLIT_THEME_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SECONDARY_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_FONT"] del os.environ["STREAMLIT_THEME_HEADING_FONT"] del os.environ["STREAMLIT_THEME_CODE_FONT"] del os.environ["STREAMLIT_THEME_DARK_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_DARK_CODE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_DARK_CODE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_DARK_LINK_COLOR"] @pytest.mark.usefixtures("configure_custom_dark_theme") def test_auto_theme_with_dark_preference( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the auto theme is the Custom Theme Dark when the system preference is dark.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_theme_auto_dark", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_dark_theme") def test_custom_dark_theme(app: Page, assert_snapshot: ImageCompareFunction): """Test that the custom dark theme is rendered correctly.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Change the theme to explicitly be Custom Dark Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Dark").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot(app, name="custom_dark_themed_app", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_dark_theme") def test_custom_light_theme_with_no_light_configs( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the custom light theme is rendered correctly with no light configs.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Switch to Custom Light Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Light").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot( app, name="custom_light_theme_no_light_configs", image_threshold=0.0003 )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_dark_theme_test.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_light_sidebar_theme_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction, wait_for_app_run from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_light_sidebar_theme(): """Configure custom light theme.""" # [theme] configs os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] = "14" os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] = "#1a6ce7" os.environ["STREAMLIT_THEME_TEXT_COLOR"] = "#1e252f" # [theme.light] configs os.environ["STREAMLIT_THEME_LIGHT_BACKGROUND_COLOR"] = "#ffffff" os.environ["STREAMLIT_THEME_LIGHT_SECONDARY_BACKGROUND_COLOR"] = "#f7f7f7" os.environ["STREAMLIT_THEME_LIGHT_BORDER_COLOR"] = "#d5dae4" os.environ["STREAMLIT_THEME_LIGHT_FONT"] = ( "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, " "sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_LIGHT_HEADING_FONT"] = ( "bold Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, " "Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_LIGHT_CODE_FONT"] = ( '"Monaspace Argon", Menlo, Monaco, Consolas, "Courier New", monospace' ) # [theme.sidebar] configs os.environ["STREAMLIT_THEME_SIDEBAR_BACKGROUND_COLOR"] = ( "#bfbbbb" # Should override [theme.light] config - light gray ) os.environ["STREAMLIT_THEME_SIDEBAR_BORDER_COLOR"] = ( "#000000" # Should apply - black ) os.environ["STREAMLIT_THEME_SIDEBAR_DATAFRAME_BORDER_COLOR"] = ( "#FF69B4" # Should apply - hot pink ) # [theme.light.sidebar] configs os.environ["STREAMLIT_THEME_LIGHT_SIDEBAR_BORDER_COLOR"] = ( "#ff6700" # hazard orange - should override [theme.light] & [theme.sidebar] configs ) os.environ["STREAMLIT_THEME_LIGHT_SIDEBAR_LINK_COLOR"] = "#7851A9" # royal purple yield del os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] del os.environ["STREAMLIT_THEME_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_SECONDARY_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_FONT"] del os.environ["STREAMLIT_THEME_LIGHT_HEADING_FONT"] del os.environ["STREAMLIT_THEME_LIGHT_CODE_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_DATAFRAME_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_SIDEBAR_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_SIDEBAR_LINK_COLOR"] @pytest.mark.usefixtures("configure_custom_light_sidebar_theme") def test_auto_sidebar_theme_with_light_preference( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the auto sidebar theme is the Custom Theme Light when the system preference is light.""" # Browser preference should be light by default is_light_mode = app.evaluate("matchMedia('(prefers-color-scheme: light)').matches") assert is_light_mode is True # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_light_sidebar_theme_auto", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_light_sidebar_theme") def test_custom_light_sidebar_theme(app: Page, assert_snapshot: ImageCompareFunction): """Test that the custom light sidebar theme is rendered correctly.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Change the theme to explicitly be Custom Light Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Light").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot(app, name="custom_light_sidebar_theme", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_light_sidebar_theme") def test_custom_dark_sidebar_theme_with_no_dark_configs( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the custom dark sidebar theme is rendered correctly with no dark configs.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Switch to Custom Dark Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Dark").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot( app, name="custom_dark_sidebar_theme_no_dark_configs", image_threshold=0.0003 )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_light_sidebar_theme_test.py", "license": "Apache License 2.0", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_light_theme_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ( ImageCompareFunction, wait_for_app_loaded, wait_for_app_run, ) from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_light_theme(): """Configure custom light theme.""" # [theme] configs os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] = "#1a6ce7" os.environ["STREAMLIT_THEME_BACKGROUND_COLOR"] = "#ffffff" os.environ["STREAMLIT_THEME_SECONDARY_BACKGROUND_COLOR"] = "#f7f7f7" os.environ["STREAMLIT_THEME_TEXT_COLOR"] = "#1e252f" os.environ["STREAMLIT_THEME_BORDER_COLOR"] = "#d5dae4" os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] = "14" os.environ["STREAMLIT_THEME_FONT"] = ( "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, " "sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_HEADING_FONT"] = ( "bold Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, " "Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" ) os.environ["STREAMLIT_THEME_CODE_FONT"] = ( '"Monaspace Argon", Menlo, Monaco, Consolas, "Courier New", monospace' ) # [theme.light] configs os.environ["STREAMLIT_THEME_LIGHT_BORDER_COLOR"] = ( "#ff6700" # hazard orange - should override [theme] config above ) os.environ["STREAMLIT_THEME_LIGHT_CODE_FONT_SIZE"] = "13px" os.environ["STREAMLIT_THEME_LIGHT_CODE_TEXT_COLOR"] = "#FF69B4" # hot pink os.environ["STREAMLIT_THEME_LIGHT_LINK_COLOR"] = "#89CFF0" # baby blue # [ theme.dark] config to test theme persistence on reload os.environ["STREAMLIT_THEME_DARK_PRIMARY_COLOR"] = "#228B22" os.environ["STREAMLIT_THEME_DARK_BORDER_COLOR"] = "#ff6700" # hazard orange os.environ["STREAMLIT_THEME_DARK_CODE_FONT_SIZE"] = "13px" os.environ["STREAMLIT_THEME_DARK_CODE_TEXT_COLOR"] = "#FF69B4" # hot pink os.environ["STREAMLIT_THEME_DARK_LINK_COLOR"] = "#89CFF0" # baby blue yield del os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] del os.environ["STREAMLIT_THEME_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SECONDARY_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_FONT"] del os.environ["STREAMLIT_THEME_HEADING_FONT"] del os.environ["STREAMLIT_THEME_CODE_FONT"] del os.environ["STREAMLIT_THEME_LIGHT_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_CODE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_LIGHT_CODE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_LIGHT_LINK_COLOR"] del os.environ["STREAMLIT_THEME_DARK_PRIMARY_COLOR"] del os.environ["STREAMLIT_THEME_DARK_BORDER_COLOR"] del os.environ["STREAMLIT_THEME_DARK_CODE_FONT_SIZE"] del os.environ["STREAMLIT_THEME_DARK_CODE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_DARK_LINK_COLOR"] @pytest.mark.usefixtures("configure_custom_light_theme") def test_auto_theme_with_light_preference( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the auto theme is the Custom Theme Light when the system preference is light.""" # Browser preference should be light by default is_light_mode = app.evaluate("matchMedia('(prefers-color-scheme: light)').matches") assert is_light_mode is True # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_theme_auto_light", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_light_theme") def test_custom_light_theme(app: Page, assert_snapshot: ImageCompareFunction): """Test that the custom light theme is rendered correctly.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Change the theme to explicitly be Custom Light Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Light").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot(app, name="custom_light_themed_app", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_light_theme") def test_custom_dark_theme_with_dark_configs( app: Page, assert_snapshot: ImageCompareFunction ): """Test that the custom dark theme is rendered correctly with expected dark configs.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Switch to Custom Dark Theme via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") menu.get_by_role("menuitemradio", name="Dark").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot( app, name="custom_dark_theme_with_dark_configs", image_threshold=0.0003 ) @pytest.mark.usefixtures("configure_custom_light_theme") def test_theme_preference_persists_on_reload( app: Page, assert_snapshot: ImageCompareFunction ): """Test that custom theme selection persists across full page reload (issue #13280).""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Select "Dark" theme explicitly via the main menu: app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") # Verify "System" is currently selected (auto theme) system_radio = menu.get_by_role("menuitemradio", name="System") expect(system_radio).to_have_attribute("aria-checked", "true") menu.get_by_role("menuitemradio", name="Dark").click() app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() wait_for_app_run(app) assert_snapshot(app, name="persisted_on_reload_before", image_threshold=0.0003) # Force a full page reload app.reload() # Wait for the app to fully load again after reload wait_for_app_loaded(app) # Open the main menu to verify theme selection persisted app.get_by_test_id("stMainMenu").click() menu = app.get_by_role("menu", name="Main menu") # Verify "Dark" is still selected after reload dark_radio = menu.get_by_role("menuitemradio", name="Dark") expect(dark_radio).to_have_attribute("aria-checked", "true") # Close the menu app.keyboard.press("Escape") expect(app.get_by_test_id("stMainMenuPopover")).not_to_be_visible() assert_snapshot(app, name="persisted_on_reload_after", image_threshold=0.0003)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_light_theme_test.py", "license": "Apache License 2.0", "lines": 149, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_space.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, cast import streamlit as st if TYPE_CHECKING: from streamlit.elements.lib.layout_utils import Gap SPACES = cast( "list[Gap]", [ "xxsmall", "xsmall", "small", "medium", "large", "xlarge", "xxlarge", ], ) st.write("Tests Outside of Containers") for space_names in SPACES: with st.expander(f"Space set to {space_names}", expanded=True): st.button(f"Before {space_names} space") st.space(space_names) st.button(f"After {space_names} space") st.divider() with st.container(horizontal=True, border=True, key="horizontal_container_space"): st.markdown("Left", width="content") st.space("medium") st.markdown("After medium space", width="content") st.space("stretch") st.markdown("After stretch space", width="content") # vertical container with stretch space with st.container(height=400, key="vertical_container_space"): st.space(25) st.write("After 25px space") st.space("stretch") st.write("After stretch space") st.space() st.write("After default small space") st.divider() st.header("Nested Container Test") with st.container(border=True, key="nested_container_space"): st.write("Outer container") st.space("large") with st.container(border=True, horizontal=True): st.button("Inner Left") st.space("stretch") st.button("Inner Right") st.space("medium") st.write("Bottom of outer container") st.divider() st.header("Frontend/Backend Size Sync Test") st.write( "This section validates that space sizes match actual widget heights " "from the frontend theme (sizes.ts)." ) # Test medium space (2.5rem) matches minElementHeight (used by buttons, inputs) # Test large space (4.25rem) matches largestElementHeight (used by file uploader, audio input) with st.container(key="size_sync_test"): st.button("Reference button", key="sync_button") st.space("medium") st.file_uploader("Reference uploader", key="sync_uploader") st.space("large")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_space.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_space_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections.abc import Callable from playwright.sync_api import Locator, Page, expect from e2e_playwright.conftest import ImageCompareFunction, wait_until from e2e_playwright.shared.app_utils import get_element_by_key def test_space_elements_exist(app: Page): """Test that space elements are rendered with correct dimensions.""" space_elements = app.get_by_test_id("stSpace") # We have multiple space elements in the test app expect(space_elements.first).to_be_attached() # Verify space elements have no visible content first_space = space_elements.first expect(first_space).to_have_text("") heights_em = [0.25, 0.5, 0.75, 2.5, 4.25, 6, 8] # Check the first space elements (in vertical layout, so height should # be set) def wait_condition(space: Locator, height_px: int) -> Callable[[], bool]: return lambda: ( (bbox := space.bounding_box()) is not None and int(bbox["height"]) == height_px ) for i, height_em in enumerate(heights_em): height_px = round(height_em * 16) space = space_elements.nth(i) wait_until(app, wait_condition(space, height_px)) def test_horizontal_container_spacing(app: Page, assert_snapshot: ImageCompareFunction): """Test horizontal spacing with medium and stretch in a horizontal container.""" horizontal_container = get_element_by_key(app, "horizontal_container_space") expect(horizontal_container).to_be_attached() # Snapshot the horizontal container to show medium and stretch spacing assert_snapshot(horizontal_container, name="st_space_horizontal_container") def test_vertical_container_with_stretch( app: Page, assert_snapshot: ImageCompareFunction ): """Test vertical spacing including stretch in a fixed-height vertical container.""" vertical_container = get_element_by_key(app, "vertical_container_space") expect(vertical_container).to_be_attached() # Snapshot shows 25px space, stretch space, and default small space assert_snapshot(vertical_container, name="st_space_vertical_container_stretch") def test_nested_containers_with_space(app: Page, assert_snapshot: ImageCompareFunction): """Test that space works correctly in nested containers with different directions.""" # Get the nested container with outer vertical and inner horizontal nested_container = get_element_by_key(app, "nested_container_space") expect(nested_container).to_be_attached() # Visual snapshot to verify spacing adapts to direction in nested contexts: # - Outer container: vertical spacing with large and medium # - Inner horizontal container: horizontal stretch spacing assert_snapshot(nested_container, name="st_space_nested_containers") def test_space_sizes_match_widget_heights(app: Page): """Test that space sizes match actual widget heights from frontend theme. This definitively proves frontend/backend sync by comparing rendered heights: - st.space("medium") height vs button height (both use minElementHeight: 2.5rem) - st.space("large") height vs file uploader height (both use largestElementHeight: 4.25rem) If this test fails, the constants have diverged between: - Backend: streamlit/elements/lib/layout_utils.py SIZE_TO_REM_MAPPING - Frontend: frontend/lib/src/theme/primitives/sizes.ts """ button = get_element_by_key(app, "sync_button").locator("button") # Get the file uploader dropzone - this is the element that uses largestElementHeight uploader_dropzone = get_element_by_key(app, "sync_uploader").get_by_test_id( "stFileUploaderDropzone" ) sync_container = get_element_by_key(app, "size_sync_test") space_elements = sync_container.get_by_test_id("stSpace") expect(button).to_be_attached() expect(uploader_dropzone).to_be_attached() expect(space_elements.first).to_be_attached() wait_until( app, lambda: ( button.bounding_box() is not None and uploader_dropzone.bounding_box() is not None and space_elements.nth(0).bounding_box() is not None and space_elements.nth(1).bounding_box() is not None ), ) button_box = button.bounding_box() dropzone_box = uploader_dropzone.bounding_box() medium_space_box = space_elements.nth(0).bounding_box() large_space_box = space_elements.nth(1).bounding_box() assert button_box is not None assert dropzone_box is not None assert medium_space_box is not None assert large_space_box is not None # Verify button height (frontend minElementHeight = 2.5rem = 40px) button_height = int(button_box["height"]) assert button_height == 40, f"Button height is {button_height}, expected 40" # Verify medium space matches button height (proves SIZE_TO_REM_MAPPING sync) medium_space_height = int(medium_space_box["height"]) assert medium_space_height == button_height, ( f"Medium space height ({medium_space_height}px) doesn't match " f"button height ({button_height}px). This means SIZE_TO_REM_MAPPING " f"'medium' is out of sync with frontend sizes.ts minElementHeight." ) # Verify file uploader dropzone height (frontend largestElementHeight = 4.25rem = 68px) dropzone_height = int(dropzone_box["height"]) assert dropzone_height == 68, ( f"File uploader dropzone height is {dropzone_height}, expected 68" ) # Verify large space matches dropzone height (proves SIZE_TO_REM_MAPPING sync) # Direct comparison: both rendered heights should be exactly 68px large_space_height = int(large_space_box["height"]) assert large_space_height == dropzone_height, ( f"Large space height ({large_space_height}px) doesn't match " f"file uploader dropzone height ({dropzone_height}px). This means " f"SIZE_TO_REM_MAPPING 'large' is out of sync with frontend " f"sizes.ts largestElementHeight." )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_space_test.py", "license": "Apache License 2.0", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/elements/space.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, cast from streamlit.elements.lib.layout_utils import ( LayoutConfig, SpaceSize, validate_space_size, ) from streamlit.proto.Space_pb2 import Space as SpaceProto from streamlit.runtime.metrics_util import gather_metrics if TYPE_CHECKING: from streamlit.delta_generator import DeltaGenerator class SpaceMixin: @gather_metrics("space") def space( self, size: SpaceSize = "small", ) -> DeltaGenerator: """Add vertical or horizontal space. This command adds space in the direction of its parent container. In a vertical layout, it adds vertical space. In a horizontal layout, it adds horizontal space. Parameters ---------- size : "xxsmall", "xsmall", "small", "medium", "large", "xlarge", "xxlarge", "stretch", or int The size of the space. This can be one of the following values: - ``"xxsmall"``: 0.25rem, matching the ``"xxsmall"`` gap in ``st.container`` and ``st.columns``. - ``"xsmall"``: 0.5rem, matching the ``"xsmall"`` gap in ``st.container`` and ``st.columns``. - ``"small"`` (default): 0.75rem, which is the height of a widget label. This is useful for aligning buttons with labeled widgets. - ``"medium"``: 2.5rem, which is the height of a button or (unlabeled) input field. - ``"large"``: 4.25rem, which is the height of a labeled input field or unlabeled media widget, like ``st.file_uploader``. - ``"xlarge"``: 6rem, matching the ``"xlarge"`` gap in ``st.container`` and ``st.columns``. - ``"xxlarge"``: 8rem, matching the ``"xxlarge"`` gap in ``st.container`` and ``st.columns``. - ``"stretch"``: Expands to fill remaining space in the container. - An integer: Fixed size in pixels. Examples -------- **Example 1: Use vertical space to align elements** Use small spaces to replace label heights. Use medium spaces to replace two label heights or a button. >>> import streamlit as st >>> >>> left, middle, right = st.columns(3) >>> >>> left.space("medium") >>> left.button("Left button", width="stretch") >>> >>> middle.space("small") >>> middle.text_input("Middle input") >>> >>> right.audio_input("Right uploader") .. output:: https://doc-space-vertical.streamlit.app/ height: 260px **Example 2: Add horizontal space in a container** Use stretch space to float elements left and right. >>> import streamlit as st >>> >>> with st.container(horizontal=True): ... st.button("Left") ... st.space("stretch") ... st.button("Right") .. output:: https://doc-space-horizontal.streamlit.app/ height: 200px """ space_proto = SpaceProto() validate_space_size(size) # In vertical layouts, size controls height. # In horizontal layouts, size controls width. # We set both width and height configs to the same size value. # The frontend uses FlexContext to determine container direction and # applies ONLY the relevant dimension (width for horizontal, height for vertical) # to avoid unintended cross-axis spacing. layout_config = LayoutConfig(width=size, height=size) return self.dg._enqueue("space", space_proto, layout_config=layout_config) @property def dg(self) -> DeltaGenerator: """Get our DeltaGenerator.""" return cast("DeltaGenerator", self)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/elements/space.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/elements/space_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from parameterized import parameterized import streamlit as st from streamlit.errors import StreamlitInvalidSizeError from tests.delta_generator_test_case import DeltaGeneratorTestCase class SpaceTest(DeltaGeneratorTestCase): """Test ability to marshall space protos.""" def test_space_default(self): """Test st.space() with default size.""" st.space() c = self.get_delta_from_queue().new_element assert c.space is not None # Default is "small" = 0.75rem assert c.width_config.rem_width == 0.75 assert c.height_config.rem_height == 0.75 @parameterized.expand( [ ("xxsmall", 0.25), ("xsmall", 0.5), ("small", 0.75), ("medium", 2.5), ("large", 4.25), ("xlarge", 6), ("xxlarge", 8), ] ) def test_space_rem_sizes(self, size_name, expected_rem): """Test space with rem size literals.""" st.space(size_name) c = self.get_delta_from_queue().new_element assert c.space is not None assert c.width_config.rem_width == expected_rem assert c.height_config.rem_height == expected_rem def test_space_stretch(self): """Test space with stretch size.""" st.space("stretch") c = self.get_delta_from_queue().new_element assert c.space is not None assert c.width_config.use_stretch assert c.height_config.use_stretch @parameterized.expand( [ 100, 50, 1, ] ) def test_space_pixel_sizes(self, pixel_value): """Test space with pixel sizes.""" st.space(pixel_value) c = self.get_delta_from_queue().new_element assert c.space is not None assert c.width_config.pixel_width == pixel_value assert c.height_config.pixel_height == pixel_value @parameterized.expand( [ "invalid", -100, 0, 100.5, # Floats not supported -50.5, None, ] ) def test_space_invalid_sizes(self, invalid_size): """Test that invalid size values raise an exception.""" with pytest.raises(StreamlitInvalidSizeError): st.space(invalid_size)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/elements/space_test.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:.claude/hooks/pre_bash_redirect.py
#!/usr/bin/env python3 # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PreToolUse(Bash) hook: block pytest commands for e2e_playwright and redirect to make targets. Exit code semantics (as of Claude Code hooks): - exit 0: allow tool call - exit 2: BLOCK; stderr is fed back to Claude so it corrects its plan automatically """ import json import re import sys # Pattern to match pytest commands, including: # - pytest # - python -m pytest # - python3 -m pytest # - with optional whitespace variations PYTEST_PATTERN = re.compile( r""" ^ # start of string (?: # non-capturing group for optional python invocation python # 'python' (?:3)? # optional '3' \s+ # whitespace -m # '-m' \s+ # whitespace )? pytest # 'pytest' \b # word boundary """, re.IGNORECASE | re.VERBOSE, ) def main() -> None: try: payload = json.load(sys.stdin) except Exception as e: # Fail secure: block (exit 2) if we can't parse input to verify safety. print( # noqa: T201 f"Policy: Failed to parse hook input ({type(e).__name__}: {e}). " f"Blocking tool call for safety.", file=sys.stderr, ) sys.exit(2) if payload.get("hook_event_name") != "PreToolUse": sys.exit(0) if payload.get("tool_name") != "Bash": sys.exit(0) cmd = (payload.get("tool_input") or {}).get("command", "") or "" norm = re.sub(r"\s+", " ", cmd).strip() # Check if this is a pytest command targeting e2e_playwright if PYTEST_PATTERN.search(norm) and "e2e_playwright" in norm: print( # noqa: T201 f"Policy: Bash('{norm}') is blocked.\n" f"E2E tests should use 'make run-e2e-test <filename>' instead.\n", file=sys.stderr, ) sys.exit(2) sys.exit(0) if __name__ == "__main__": main()
{ "repo_id": "streamlit/streamlit", "file_path": ".claude/hooks/pre_bash_redirect.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/custom_url_base.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from theme_tester_app import run_theme_tester_app # type: ignore run_theme_tester_app()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_url_base.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/custom_url_base_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_font, expect_no_skeletons # ruff: noqa: ERA001 # The theme.base points to a toml file hosted on our streamlit s3 bucket # It has the following fields set: # [theme] # base = "light" # font = "Ojuju:https://fonts.googleapis.com/css2?family=Ojuju:wght@200..800&display=swap" # primaryColor = "#0013de" # blue # secondaryBackgroundColor = "#d8e4ee" # light grayish blue # textColor = "#05014a" # dark blue # [theme.sidebar] # linkColor = "#FF7518" # Pumpkin orange @pytest.fixture(scope="module") @pytest.mark.early def configure_base_and_config_custom_theme(): """Configure custom theme - with base pointing to url and config overrides.""" os.environ["STREAMLIT_THEME_BASE"] = "https://data.streamlit.io/corporate.toml" os.environ["STREAMLIT_THEME_LINK_COLOR"] = "#CD1C18" # Chili red os.environ["STREAMLIT_THEME_CODE_BACKGROUND_COLOR"] = ( "#eeeaef" # Light grayish purple ) os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] = ( "Oswald:https://fonts.googleapis.com/css2?family=Oswald:wght@200..700&display=swap" ) os.environ["STREAMLIT_THEME_SIDEBAR_LINK_COLOR"] = "#7851A9" # Royal purple yield del os.environ["STREAMLIT_THEME_BASE"] del os.environ["STREAMLIT_THEME_LINK_COLOR"] del os.environ["STREAMLIT_THEME_CODE_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_LINK_COLOR"] @pytest.mark.usefixtures("configure_base_and_config_custom_theme") def test_custom_theme_with_url_base(app: Page, assert_snapshot: ImageCompareFunction): """Test that custom theme with theme.base = <url> loads correctly and applies theme inheritance.""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Verify that fonts from external TOML file have loaded: expect_font(app, "Ojuju", style="normal") # Verify that fonts from local config overrides have loaded: expect_font(app, "Oswald", style="normal") assert_snapshot(app, name="custom_theme_with_url_base", image_threshold=0.0003)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_url_base_test.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_vega_charts_height.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import altair as alt import pandas as pd import streamlit as st # Test data simple_df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T simple_spec = { "mark": "bar", "encoding": { "x": {"field": "a", "type": "ordinal"}, "y": {"field": "b", "type": "quantitative"}, }, } st.header("Vega Charts Height Tests") # Test explicit height parameters st.subheader("Explicit Height Parameter Tests") # Add some additional text to remove flakiness in firefox caused by subpixel sizing: st.write("Testing different height parameters for vega charts") st.write("Chart with height='content':") st.vega_lite_chart(simple_df, simple_spec, height="content") st.write("Chart with height='stretch':") with st.container(border=True, key="test_height_stretch", height=500): st.vega_lite_chart(simple_df, simple_spec, height="stretch") st.write("Chart with height=150:") st.vega_lite_chart(simple_df, simple_spec, height=150) # Test chart with height in spec vs height parameter spec_with_height = { "mark": "bar", "encoding": { "x": {"field": "a", "type": "ordinal"}, "y": {"field": "b", "type": "quantitative"}, }, "height": 200, } st.write("Chart with height in spec (200) and height='content' parameter:") st.vega_lite_chart(simple_df, spec_with_height, height="content") st.write("Chart with height in spec (200) and height='stretch' parameter:") with st.container(border=True, key="test_height_stretch_with_spec", height=400): st.vega_lite_chart(simple_df, spec_with_height, height="stretch") st.write("Chart with height in spec (200) and height=100 parameter:") st.vega_lite_chart(simple_df, spec_with_height, height=100) st.write("Vertical concatenation chart:") vconcat_spec = { "vconcat": [ { "mark": "bar", "encoding": { "x": {"field": "a", "type": "ordinal"}, "y": {"field": "b", "type": "quantitative"}, }, }, { "mark": "point", "encoding": { "x": {"field": "a", "type": "ordinal"}, "y": {"field": "b", "type": "quantitative"}, }, }, ] } st.vega_lite_chart(simple_df, vconcat_spec) # Test st.altair_chart with fixed height st.write("Altair chart with height=250:") chart = ( alt.Chart(simple_df) .mark_bar() .encode( x=alt.X("a:O"), y=alt.Y("b:Q"), ) ) st.altair_chart(chart, height=250) st.write("Altair chart with height in spec (180) and height='content' parameter:") content_chart = ( alt.Chart(simple_df) .mark_circle(size=100) .encode( x=alt.X("a:O"), y=alt.Y("b:Q"), ) .properties(height=180) ) st.altair_chart(content_chart, height="content") st.write("Altair chart with height='stretch':") with st.container(border=True, key="test_altair_height_stretch", height=500): stretch_chart = ( alt.Chart(simple_df) .mark_area() .encode( x=alt.X("a:O"), y=alt.Y("b:Q"), ) ) st.altair_chart(stretch_chart, height="stretch") # Test scatter chart height parameters st.subheader("Scatter Chart Height Tests") scatter_df = pd.DataFrame( { "x": [1, 2, 3, 4, 5], "y": [2, 5, 3, 8, 7], "size": [20, 40, 30, 60, 50], } ) st.write("Scatter chart with height='content':") st.scatter_chart(scatter_df, x="x", y="y", size="size", height="content") st.write("Scatter chart with height='stretch':") with st.container(border=True, key="test_scatter_height_stretch", height=400): st.scatter_chart(scatter_df, x="x", y="y", size="size", height="stretch") st.write("Bar chart with height='content':") st.bar_chart(scatter_df, x="x", y="y", height="content") st.write("Bar chart with height='stretch':") with st.container(border=True, key="test_bar_height_stretch", height=400): st.bar_chart(scatter_df, x="x", y="y", height="stretch") st.write("Area chart with height='content':") st.area_chart(scatter_df, x="x", y="y", height="content") st.write("Area chart with height='stretch':") with st.container(border=True, key="test_area_height_stretch", height=400): st.area_chart(scatter_df, x="x", y="y", height="stretch")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_vega_charts_height.py", "license": "Apache License 2.0", "lines": 130, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_vega_charts_height_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import check_top_level_class, get_element_by_key from e2e_playwright.shared.vega_utils import assert_vega_chart_height VEGA_CHART_COUNT = 16 def test_vega_chart_height_behavior(app: Page): """Tests that charts have correct height behavior for both default and explicit heights.""" vega_lite_charts = app.get_by_test_id("stVegaLiteChart") expect(vega_lite_charts).to_have_count(VEGA_CHART_COUNT) expected_heights = [ 350, # 0: Chart with height='content' 468, # 1: Chart with height='stretch' (in 500px container, minus padding) 150, # 2: Chart with height=150 200, # 3: Chart with height in spec (200) and height='content' parameter 368, # 4: Chart with height in spec (200) and height='stretch' parameter (in 400px container) 100, # 5: Chart with height in spec (200) and height=100 parameter 852, # 6: Vertical concatenation chart with default height (content) 250, # 7: Altair chart with height=250 180, # 8: Altair chart with height in spec (180) and height='content' parameter 468, # 9: Altair chart with height='stretch' (in 500px container, minus padding) 350, # 10: Scatter chart with height='content' 368, # 11: Scatter chart with height='stretch' (in 400px container, minus padding) 350, # 12: Bar chart with height='content' 368, # 13: Bar chart with height='stretch' (in 400px container, minus padding) 350, # 12: Area chart with height='content' 368, # 13: Area chart with height='stretch' (in 400px container, minus padding) ] descriptions = [ "Chart with height='content'", "Chart with height='stretch' (in 500px container)", "Chart with height=150", "Chart with height in spec (200) and height='content' parameter", "Chart with height in spec (200) and height='stretch' parameter (in 400px container)", "Chart with height in spec (200) and height=100 parameter", "Vertical concatenation chart with default height (content)", "Altair chart with height=250", "Altair chart with height in spec (180) and height='content' parameter", "Altair chart with height='stretch' (in 500px container)", "Scatter chart with height='content'", "Scatter chart with height='stretch' (in 400px container)", "Bar chart with height='content'", "Bar chart with height='stretch' (in 400px container)", "Area chart with height='content'", "Area chart with height='stretch' (in 400px container)", ] for i, expected_height in enumerate(expected_heights): chart = vega_lite_charts.nth(i) expect(chart).to_be_visible() chart_description = f"Chart {i}: {descriptions[i]}" # Note: tolerance is included below to account for some small pixel differences that can occur # due to sizing by the charting library and stretch height rounding. assert_vega_chart_height(chart, expected_height, chart_description, tolerance=3) def test_vega_chart_height_content_snapshot( app: Page, assert_snapshot: ImageCompareFunction ): """Tests height='content' parameter visual appearance.""" vega_lite_charts = app.get_by_test_id("stVegaLiteChart") expect(vega_lite_charts).to_have_count(VEGA_CHART_COUNT) expect(vega_lite_charts.nth(0)).to_be_visible() assert_snapshot( vega_lite_charts.nth(0), name="st_vega_charts_height-height_content", ) def test_vega_chart_height_stretch_snapshot( app: Page, assert_snapshot: ImageCompareFunction ): """Tests height='stretch' parameter visual appearance.""" vega_lite_charts = app.get_by_test_id("stVegaLiteChart") expect(vega_lite_charts).to_have_count(VEGA_CHART_COUNT) expect(get_element_by_key(app, "test_height_stretch")).to_be_visible() assert_snapshot( vega_lite_charts.nth(1), name="st_vega_charts_height-height_stretch", ) def test_vega_chart_height_150px_snapshot( app: Page, assert_snapshot: ImageCompareFunction ): """Tests height=150 parameter visual appearance.""" vega_lite_charts = app.get_by_test_id("stVegaLiteChart") expect(vega_lite_charts).to_have_count(VEGA_CHART_COUNT) expect(vega_lite_charts.nth(2)).to_be_visible() assert_snapshot( vega_lite_charts.nth(2), name="st_vega_charts_height-height_150px", ) def test_check_top_level_class(app: Page): """Check that the top level class is correctly set.""" check_top_level_class(app, "stVegaLiteChart")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_vega_charts_height_test.py", "license": "Apache License 2.0", "lines": 101, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_text_colors.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import streamlit as st np.random.seed(0) # Create random sparkline data: def generate_sparkline_data( length: int = 30, drift: float = 0.1, volatility: float = 10 ) -> list[float]: random_changes = np.random.normal(loc=drift, scale=volatility, size=length) initial_value = np.random.normal(loc=50, scale=5) data = initial_value + np.cumsum(random_changes) return data.tolist() # type: ignore st.set_page_config(initial_sidebar_state="expanded", layout="wide") # Better show the app content by minimizing the dead space st.html(""" <style> .stMainBlockContainer { padding-top: 4rem; } </style> """) st.header("Custom Text Colors :rainbow[App]") def page1(): pass def page2(): pass st.navigation( [ st.Page(page1, title="Page 1", icon=":material/home:"), st.Page(page2, title="Page 2", icon=":material/settings:"), ] ) @st.dialog("My Dialog") def my_dialog(): st.write("Hello World") col1, col2, col3, col4 = st.columns(4) with col1: if st.button("Open Dialog", width="stretch"): my_dialog() st.segmented_control( "Segmented Control", options=["Option 1", "Option 2"], default="Option 1", label_visibility="collapsed", ) st.button("Primary Button", type="primary") st.divider() st.write("**Alerts:**") st.info("Info") st.warning("Warning") st.error("Error") st.success("Success") st.write("Badges:") c1, c2, c3 = st.columns(3) with c1: st.badge("Blue", color="blue") st.badge("Green", color="green") st.badge("Gray", color="gray") with c2: st.badge("Yellow", color="yellow") st.badge("Red", color="red") with c3: st.badge("Violet", color="violet") st.badge("Orange", color="orange") with col2: with st.expander("Expander", expanded=True): st.write("Chat Message avatars (main colors):") user_message = st.chat_message(name="User") user_message.write("Hello Kevin!") assistant_message = st.chat_message(name="Assistant") assistant_message.write("Hello :dog:") st.container(key="markdown").markdown( r""" Text colors for markdown: - :blue[blue], :green[green], :yellow[yellow], :red[red], :violet[violet], :orange[orange], :gray[gray], :grey[grey], :primary[primary], :rainbow[rainbow] """ ) st.container(key="badge_markdown").markdown( r""" Markdown badges: - :blue-badge[blue], :green-badge[green], :yellow-badge[yellow], :red-badge[red], :violet-badge[violet], :orange-badge[orange], :gray-badge[gray], :primary-badge[primary] """ ) with col3: st.subheader("Dividers - Main Colors:") st.subheader("Red test", divider="red") st.subheader("Orange test", divider="orange") st.subheader("Yellow test", divider="yellow") st.subheader("Green test", divider="green") st.subheader("Blue test", divider="blue") st.subheader("Violet test", divider="violet") st.subheader("Gray test", divider="gray") with st.sidebar: st.subheader("Text colors:") st.container(key="sidebar_markdown").markdown( r""" Markdown text colors: - :blue[blue], :green[green], :yellow[yellow], :red[red], :violet[violet], :orange[orange], :gray[gray], :grey[grey], :primary[primary], :rainbow[rainbow] """ ) st.write("**Badges:**") c1, c2, c3 = st.columns(3) with c1: st.badge("Blue", color="blue") st.badge("Green", color="green") st.badge("Gray", color="gray") with c2: st.badge("Yellow", color="yellow") st.badge("Red", color="red") with c3: st.badge("Violet", color="violet") st.badge("Orange", color="orange") st.subheader("Dividers - Main Colors:") st.subheader("Red test", divider="red") st.subheader("Orange test", divider="orange") st.subheader("Yellow test", divider="yellow") st.subheader("Green test", divider="green") st.subheader("Blue test", divider="blue") st.subheader("Violet test", divider="violet") st.subheader("Gray test", divider="gray") with col4: st.metric( "User growth", 123, 123, delta_color="normal", chart_data=generate_sparkline_data(), chart_type="bar", border=True, ) st.metric( "S&P 500", -4.56, -50, chart_data=generate_sparkline_data(), chart_type="area", border=True, ) st.metric( "Apples I've eaten", "23k", " -20", delta_color="off", chart_data=generate_sparkline_data(), chart_type="line", border=True, )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_text_colors.py", "license": "Apache License 2.0", "lines": 164, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/custom_text_colors_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_theme_text_colors(): """Configure custom theme text colors.""" # Main theme text colors (medium intensity) os.environ["STREAMLIT_THEME_RED_TEXT_COLOR"] = "#e74c3c" os.environ["STREAMLIT_THEME_ORANGE_TEXT_COLOR"] = "#f39c12" os.environ["STREAMLIT_THEME_YELLOW_TEXT_COLOR"] = "#f1c40f" os.environ["STREAMLIT_THEME_BLUE_TEXT_COLOR"] = "#3498db" os.environ["STREAMLIT_THEME_GREEN_TEXT_COLOR"] = "#27ae60" os.environ["STREAMLIT_THEME_VIOLET_TEXT_COLOR"] = "#9b59b6" os.environ["STREAMLIT_THEME_GRAY_TEXT_COLOR"] = "#7f8c8d" # Sidebar text colors (much darker/more saturated for clear distinction) os.environ["STREAMLIT_THEME_SIDEBAR_RED_TEXT_COLOR"] = "#8b0000" os.environ["STREAMLIT_THEME_SIDEBAR_ORANGE_TEXT_COLOR"] = "#cc4400" os.environ["STREAMLIT_THEME_SIDEBAR_YELLOW_TEXT_COLOR"] = "#b8860b" os.environ["STREAMLIT_THEME_SIDEBAR_BLUE_TEXT_COLOR"] = "#000080" os.environ["STREAMLIT_THEME_SIDEBAR_GREEN_TEXT_COLOR"] = "#006400" os.environ["STREAMLIT_THEME_SIDEBAR_VIOLET_TEXT_COLOR"] = "#4b0082" os.environ["STREAMLIT_THEME_SIDEBAR_GRAY_TEXT_COLOR"] = "#2f2f2f" yield del os.environ["STREAMLIT_THEME_RED_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_ORANGE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_YELLOW_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_BLUE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_GREEN_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_VIOLET_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_GRAY_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_RED_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_ORANGE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_YELLOW_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_BLUE_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_GREEN_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_VIOLET_TEXT_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_GRAY_TEXT_COLOR"] @pytest.mark.usefixtures("configure_custom_theme_text_colors") def test_custom_theme_text_colors(app: Page, assert_snapshot: ImageCompareFunction): # Set bigger viewport to better show app content app.set_viewport_size({"width": 1280, "height": 1000}) # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_text_colors_app", image_threshold=0.0003)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_text_colors_test.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_background_colors.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import streamlit as st np.random.seed(0) # Create random sparkline data: def generate_sparkline_data( length: int = 30, drift: float = 0.1, volatility: float = 10 ) -> list[float]: random_changes = np.random.normal(loc=drift, scale=volatility, size=length) initial_value = np.random.normal(loc=50, scale=5) data = initial_value + np.cumsum(random_changes) return data.tolist() # type: ignore st.set_page_config(initial_sidebar_state="expanded", layout="wide") # Better show the app content by minimizing the dead space st.html(""" <style> .stMainBlockContainer { padding-top: 4rem; } </style> """) st.header("Custom Background Colors :rainbow[App]") def page1(): pass def page2(): pass st.navigation( [ st.Page(page1, title="Page 1", icon=":material/home:"), st.Page(page2, title="Page 2", icon=":material/settings:"), ] ) @st.dialog("My Dialog") def my_dialog(): st.write("Hello World") col1, col2, col3, col4 = st.columns(4) with col1: if st.button("Open Dialog", width="stretch"): my_dialog() st.segmented_control( "Segmented Control", options=["Option 1", "Option 2"], default="Option 1", label_visibility="collapsed", ) st.button("Primary Button", type="primary") st.divider() st.write("Alerts:") st.info("Info") st.warning("Warning") st.error("Error") st.success("Success") st.write("Badges:") c1, c2, c3 = st.columns(3) with c1: st.badge("Blue", color="blue") st.badge("Green", color="green") st.badge("Gray", color="gray") with c2: st.badge("Yellow", color="yellow") st.badge("Red", color="red") with c3: st.badge("Violet", color="violet") st.badge("Orange", color="orange") with col2: with st.expander("Expander", expanded=True): st.write("Chat Message avatars (main colors):") user_message = st.chat_message(name="User") user_message.write("Hello Kevin!") assistant_message = st.chat_message(name="Assistant") assistant_message.write("Hello :dog:") st.container(key="mixed_markdown").markdown( r""" Markdown background colors: - :blue-background[blue], :green-background[green], :yellow-background[yellow], :red-background[red], :violet-background[violet], :orange-background[orange], :gray-background[gray], :primary-background[primary], :rainbow-background[rainbow] """ ) st.container(key="badge_markdown").markdown( r""" Markdown badges: - :blue-badge[blue], :green-badge[green], :yellow-badge[yellow], :red-badge[red], :violet-badge[violet], :orange-badge[orange], :gray-badge[gray], :primary-badge[primary] """ ) with col3: st.subheader("Dividers - Main Colors:") st.subheader("Red test", divider="red") st.subheader("Orange test", divider="orange") st.subheader("Yellow test", divider="yellow") st.subheader("Green test", divider="green") st.subheader("Blue test", divider="blue") st.subheader("Violet test", divider="violet") st.subheader("Gray test", divider="gray") with st.sidebar: st.header("Dividers - Main Colors:") st.subheader("Red test", divider="red") st.subheader("Orange test", divider="orange") st.subheader("Yellow test", divider="yellow") st.subheader("Green test", divider="green") st.subheader("Blue test", divider="blue") st.subheader("Violet test", divider="violet") st.subheader("Gray test", divider="gray") st.divider() c1, c2 = st.columns(2) with c1: st.write("Badges:") st.badge("Blue", color="blue") st.badge("Green", color="green") st.badge("Yellow", color="yellow") with c2: st.badge("Red", color="red") st.badge("Violet", color="violet") st.badge("Orange", color="orange") st.badge("Gray", color="gray") with col4: st.metric( "User growth", 123, 123, delta_color="normal", chart_data=generate_sparkline_data(), chart_type="bar", border=True, ) st.metric( "S&P 500", -4.56, -50, chart_data=generate_sparkline_data(), chart_type="area", border=True, ) st.metric( "Apples I've eaten", "23k", " -20", delta_color="off", chart_data=generate_sparkline_data(), chart_type="line", border=True, )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_background_colors.py", "license": "Apache License 2.0", "lines": 155, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/custom_background_colors_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_theme_background_colors(): """Configure custom theme background colors.""" # Also set some main colors for better contrast with background colors # these will trigger derived text colors as well os.environ["STREAMLIT_THEME_RED_COLOR"] = "#750000" os.environ["STREAMLIT_THEME_GREEN_COLOR"] = "#008000" os.environ["STREAMLIT_THEME_GRAY_COLOR"] = "#525252" # Background colors os.environ["STREAMLIT_THEME_RED_BACKGROUND_COLOR"] = "#ffc7c7" os.environ["STREAMLIT_THEME_ORANGE_BACKGROUND_COLOR"] = "#fdae44" os.environ["STREAMLIT_THEME_YELLOW_BACKGROUND_COLOR"] = "#fde992" os.environ["STREAMLIT_THEME_BLUE_BACKGROUND_COLOR"] = "#6495ED" os.environ["STREAMLIT_THEME_GREEN_BACKGROUND_COLOR"] = "#9dc183" os.environ["STREAMLIT_THEME_VIOLET_BACKGROUND_COLOR"] = "#9E7BB5" os.environ["STREAMLIT_THEME_GRAY_BACKGROUND_COLOR"] = "#A7A6BA" os.environ["STREAMLIT_THEME_SIDEBAR_RED_BACKGROUND_COLOR"] = "#9d2933" os.environ["STREAMLIT_THEME_SIDEBAR_ORANGE_BACKGROUND_COLOR"] = "#fed8b1" os.environ["STREAMLIT_THEME_SIDEBAR_YELLOW_BACKGROUND_COLOR"] = "#ffffe0" os.environ["STREAMLIT_THEME_SIDEBAR_BLUE_BACKGROUND_COLOR"] = "#87afc7" os.environ["STREAMLIT_THEME_SIDEBAR_GREEN_BACKGROUND_COLOR"] = "#d8e4bc" os.environ["STREAMLIT_THEME_SIDEBAR_VIOLET_BACKGROUND_COLOR"] = "#D8BFD8" os.environ["STREAMLIT_THEME_SIDEBAR_GRAY_BACKGROUND_COLOR"] = "#DCDCDC" yield del os.environ["STREAMLIT_THEME_RED_COLOR"] del os.environ["STREAMLIT_THEME_GREEN_COLOR"] del os.environ["STREAMLIT_THEME_GRAY_COLOR"] del os.environ["STREAMLIT_THEME_RED_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_ORANGE_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_YELLOW_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_BLUE_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_GREEN_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_VIOLET_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_GRAY_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_RED_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_ORANGE_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_YELLOW_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_BLUE_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_GREEN_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_VIOLET_BACKGROUND_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_GRAY_BACKGROUND_COLOR"] @pytest.mark.usefixtures("configure_custom_theme_background_colors") def test_custom_theme_background_colors( app: Page, assert_snapshot: ImageCompareFunction ): # Set bigger viewport to better show app content app.set_viewport_size({"width": 1280, "height": 1000}) # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_background_colors_app", image_threshold=0.0003)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_background_colors_test.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_main_colors.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import streamlit as st np.random.seed(0) # Create random sparkline data: def generate_sparkline_data( length: int = 30, drift: float = 0.1, volatility: float = 10 ) -> list[float]: random_changes = np.random.normal(loc=drift, scale=volatility, size=length) initial_value = np.random.normal(loc=50, scale=5) data = initial_value + np.cumsum(random_changes) return data.tolist() # type: ignore st.set_page_config(initial_sidebar_state="expanded", layout="wide") # Better show the app content by minimizing the dead space st.html(""" <style> .stMainBlockContainer { padding-top: 4rem; } </style> """) st.header("Custom Colors :rainbow[App]") def page1(): pass def page2(): pass st.navigation( [ st.Page(page1, title="Page 1", icon=":material/home:"), st.Page(page2, title="Page 2", icon=":material/settings:"), ] ) @st.dialog("My Dialog") def my_dialog(): st.write("Hello World") col1, col2, col3, col4 = st.columns(4) with col1: if st.button("Open Dialog", width="stretch"): my_dialog() st.segmented_control( "Segmented Control", options=["Option 1", "Option 2"], default="Option 1", label_visibility="collapsed", ) st.button("Primary Button", type="primary") st.divider() st.code("# st.code\na = 1234") st.chat_input("Chat Input") st.multiselect( "Multiselect", options=["Option 1", "Option 2", "Option 3"], default=["Option 1"], label_visibility="collapsed", ) with col2: with st.expander("Expander", expanded=True): st.write("Chat Message avatars (main colors):") user_message = st.chat_message(name="User") user_message.write("Hello Kevin!") assistant_message = st.chat_message(name="Assistant") assistant_message.write("Hello :dog:") with col3: st.subheader("Dividers - Main Colors:") st.subheader("Red test", divider="red") st.subheader("Orange test", divider="orange") st.subheader("Yellow test", divider="yellow") st.subheader("Green test", divider="green") st.subheader("Blue test", divider="blue") st.subheader("Violet test", divider="violet") st.subheader("Gray test", divider="gray") with st.sidebar: st.header("Dividers - Main Colors:") st.subheader("Red test", divider="red") st.subheader("Orange test", divider="orange") st.subheader("Yellow test", divider="yellow") st.subheader("Green test", divider="green") st.subheader("Blue test", divider="blue") st.subheader("Violet test", divider="violet") st.subheader("Gray test", divider="gray") with col4: st.metric( "User growth", 123, 123, delta_color="normal", chart_data=generate_sparkline_data(), chart_type="bar", border=True, ) st.metric( "S&P 500", -4.56, -50, chart_data=generate_sparkline_data(), chart_type="area", border=True, ) st.metric( "Apples I've eaten", "23k", " -20", delta_color="off", chart_data=generate_sparkline_data(), chart_type="line", border=True, )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_main_colors.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/custom_main_colors_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_theme_colors(): """Configure custom theme colors.""" os.environ["STREAMLIT_THEME_RED_COLOR"] = "#7d353b" os.environ["STREAMLIT_THEME_ORANGE_COLOR"] = "#d95a00" os.environ["STREAMLIT_THEME_YELLOW_COLOR"] = "#916e10" os.environ["STREAMLIT_THEME_BLUE_COLOR"] = "#004280" os.environ["STREAMLIT_THEME_GREEN_COLOR"] = "#177233" os.environ["STREAMLIT_THEME_VIOLET_COLOR"] = "#583f84" os.environ["STREAMLIT_THEME_GRAY_COLOR"] = "#0e1117" os.environ["STREAMLIT_THEME_SIDEBAR_RED_COLOR"] = "#ffc7c7" os.environ["STREAMLIT_THEME_SIDEBAR_ORANGE_COLOR"] = "#ffd16a" os.environ["STREAMLIT_THEME_SIDEBAR_YELLOW_COLOR"] = "#ffffa0" os.environ["STREAMLIT_THEME_SIDEBAR_BLUE_COLOR"] = "#a6dcff" os.environ["STREAMLIT_THEME_SIDEBAR_GREEN_COLOR"] = "#9ef6bb" os.environ["STREAMLIT_THEME_SIDEBAR_VIOLET_COLOR"] = "#dbbbff" os.environ["STREAMLIT_THEME_SIDEBAR_GRAY_COLOR"] = "#e6eaf1" # Since main colors are configured, these are used to derive background # and text colors as well yield del os.environ["STREAMLIT_THEME_RED_COLOR"] del os.environ["STREAMLIT_THEME_ORANGE_COLOR"] del os.environ["STREAMLIT_THEME_YELLOW_COLOR"] del os.environ["STREAMLIT_THEME_BLUE_COLOR"] del os.environ["STREAMLIT_THEME_GREEN_COLOR"] del os.environ["STREAMLIT_THEME_VIOLET_COLOR"] del os.environ["STREAMLIT_THEME_GRAY_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_RED_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_ORANGE_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_YELLOW_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_BLUE_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_GREEN_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_VIOLET_COLOR"] del os.environ["STREAMLIT_THEME_SIDEBAR_GRAY_COLOR"] @pytest.mark.usefixtures("configure_custom_theme_colors") def test_custom_theme_colors(app: Page, assert_snapshot: ImageCompareFunction): # Set bigger viewport to better show app content app.set_viewport_size({"width": 1280, "height": 1000}) # Add a small timeout to allow elements to adjust to the new viewport size app.wait_for_timeout(2000) # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) assert_snapshot(app, name="custom_main_colors_app")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_main_colors_test.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/tests/streamlit/elements/lib/layout_utils_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import unittest import pytest from parameterized import parameterized from streamlit.elements.lib.layout_utils import ( SpaceSize, get_align, get_gap_size, get_height_config, get_justify, get_width_config, validate_height, validate_horizontal_alignment, validate_space_size, validate_vertical_alignment, validate_width, ) from streamlit.errors import ( StreamlitInvalidColumnGapError, StreamlitInvalidHeightError, StreamlitInvalidHorizontalAlignmentError, StreamlitInvalidSizeError, StreamlitInvalidVerticalAlignmentError, StreamlitInvalidWidthError, ) from streamlit.proto.Block_pb2 import Block from streamlit.proto.GapSize_pb2 import GapSize class LayoutUtilsTest(unittest.TestCase): @parameterized.expand( [ (1, False), (100, False), (10, True), ("stretch", False), ("content", True), ] ) def test_validate_width_valid(self, width: int | str, allow_content: bool): """validate_width accepts positive ints, 'stretch', and optionally 'content'.""" validate_width(width, allow_content=allow_content) @parameterized.expand( [ (0, False), (-1, False), ("content", False), ("invalid", False), (10.5, False), (None, False), ] ) def test_validate_width_invalid(self, width: object, allow_content: bool): """validate_width raises for non-positive ints, disallowed strings, and wrong types.""" with pytest.raises(StreamlitInvalidWidthError): validate_width(width, allow_content=allow_content) # type: ignore[arg-type] @parameterized.expand( [ (1, False, True, None), (10, False, False, None), ("stretch", False, True, None), ("content", True, True, None), ("auto", False, True, ["auto"]), ] ) def test_validate_height_valid( self, height: int | str, allow_content: bool, allow_stretch: bool, additional_allowed: list[str] | None, ): """validate_height accepts allowed ints and strings based on flags provided.""" validate_height( height, allow_content=allow_content, allow_stretch=allow_stretch, additional_allowed=additional_allowed, ) @parameterized.expand( [ (0, False, True, None), (-5, False, True, None), ("content", False, True, None), ("stretch", False, False, None), ("invalid", False, True, None), (5.5, False, True, None), ("auto", False, True, None), ] ) def test_validate_height_invalid( self, height: object, allow_content: bool, allow_stretch: bool, additional_allowed: list[str] | None, ): """validate_height raises for invalid values or when flags disallow certain strings.""" with pytest.raises(StreamlitInvalidHeightError): validate_height( height, # type: ignore[arg-type] allow_content=allow_content, allow_stretch=allow_stretch, additional_allowed=additional_allowed, ) @parameterized.expand( [ (100, 100), (100.9, 100), ] ) def test_get_width_config_numeric(self, width: float | int, expected_px: int): """get_width_config produces pixel_width for numeric inputs (floats are truncated).""" config = get_width_config(width) assert config.pixel_width == expected_px assert not config.use_content assert not config.use_stretch def test_get_width_config_zero(self): """get_width_config produces pixel_width=0 for zero input.""" config = get_width_config(0) assert config.pixel_width == 0 assert not config.use_content assert not config.use_stretch @parameterized.expand( [ ("content", True, False), ("stretch", False, True), ] ) def test_get_width_config_string( self, width: str, expect_content: bool, expect_stretch: bool ): """get_width_config sets the appropriate flags for string inputs.""" config = get_width_config(width) assert config.pixel_width == 0 assert config.use_content is expect_content assert config.use_stretch is expect_stretch @parameterized.expand( [ (200, 200), (200.7, 200), ] ) def test_get_height_config_numeric(self, height: float | int, expected_px: int): """get_height_config produces pixel_height for numeric inputs (floats are truncated).""" config = get_height_config(height) assert config.pixel_height == expected_px assert not config.use_content assert not config.use_stretch def test_get_height_config_zero(self): """get_height_config produces pixel_height=0 for zero input.""" config = get_height_config(0) assert config.pixel_height == 0 assert not config.use_content assert not config.use_stretch @parameterized.expand( [ ("content", True, False), ("stretch", False, True), ] ) def test_get_height_config_string( self, height: str, expect_content: bool, expect_stretch: bool ): """get_height_config sets the appropriate flags for string inputs.""" config = get_height_config(height) assert config.pixel_height == 0 assert config.use_content is expect_content assert config.use_stretch is expect_stretch @parameterized.expand( [ ("small", GapSize.SMALL), ("medium", GapSize.MEDIUM), ("large", GapSize.LARGE), (None, GapSize.NONE), ] ) def test_get_gap_size_valid(self, gap: str | None, expected: GapSize.ValueType): """get_gap_size maps valid inputs to GapSize values, None to GapSize.NONE.""" assert get_gap_size(gap, "st.columns") == expected def test_get_gap_size_invalid(self): """get_gap_size raises for invalid gap strings.""" with pytest.raises(StreamlitInvalidColumnGapError): get_gap_size("tiny", "st.columns") @parameterized.expand( [ ("left",), ("center",), ("right",), ("distribute",), ] ) def test_validate_horizontal_alignment_valid(self, align: str): """validate_horizontal_alignment accepts known horizontal alignment values.""" validate_horizontal_alignment(align) # type: ignore[arg-type] def test_validate_horizontal_alignment_invalid(self): """validate_horizontal_alignment raises for unknown values.""" with pytest.raises(StreamlitInvalidHorizontalAlignmentError): validate_horizontal_alignment("middle") # type: ignore[arg-type] @parameterized.expand( [ ("top",), ("center",), ("bottom",), ("distribute",), ] ) def test_validate_vertical_alignment_valid(self, align: str): """validate_vertical_alignment accepts known vertical alignment values.""" validate_vertical_alignment(align) # type: ignore[arg-type] def test_validate_vertical_alignment_invalid(self): """validate_vertical_alignment raises for unknown values.""" with pytest.raises(StreamlitInvalidVerticalAlignmentError): validate_vertical_alignment("middle") # type: ignore[arg-type] @parameterized.expand( [ ("left", Block.FlexContainer.Justify.JUSTIFY_START), ("center", Block.FlexContainer.Justify.JUSTIFY_CENTER), ("right", Block.FlexContainer.Justify.JUSTIFY_END), ("top", Block.FlexContainer.Justify.JUSTIFY_START), ("bottom", Block.FlexContainer.Justify.JUSTIFY_END), ("distribute", Block.FlexContainer.Justify.SPACE_BETWEEN), ] ) def test_get_justify(self, align: str, expected) -> None: """get_justify maps alignments to the correct Justify enum values.""" assert get_justify(align) == expected # type: ignore[arg-type] @parameterized.expand( [ ("left", Block.FlexContainer.Align.ALIGN_START), ("center", Block.FlexContainer.Align.ALIGN_CENTER), ("right", Block.FlexContainer.Align.ALIGN_END), ("top", Block.FlexContainer.Align.ALIGN_START), ("bottom", Block.FlexContainer.Align.ALIGN_END), ("distribute", Block.FlexContainer.Align.ALIGN_UNDEFINED), ] ) def test_get_align(self, align: str, expected) -> None: """get_align maps alignments to the correct Align enum values (or UNDEFINED).""" assert get_align(align) == expected # type: ignore[arg-type] @parameterized.expand( [ ("xxsmall",), ("xsmall",), ("small",), ("medium",), ("large",), ("xlarge",), ("xxlarge",), ("stretch",), (1,), (100,), ] ) def test_validate_size_valid(self, size: SpaceSize): """validate_size accepts valid size values.""" validate_space_size(size) @parameterized.expand( [ 0, -1, 50.5, # Floats not supported "invalid", None, "content", # Not valid for st.space ] ) def test_validate_size_invalid(self, size: any): """validate_size raises for invalid size values.""" with pytest.raises(StreamlitInvalidSizeError): validate_space_size(size) # type: ignore[arg-type] @parameterized.expand( [ ("xxsmall", 0.25), ("xsmall", 0.5), ("small", 0.75), ("medium", 2.5), ("large", 4.25), ("xlarge", 6), ("xxlarge", 8), ] ) def test_get_width_config_rem(self, size: str, expected_rem: float): """get_width_config handles rem values correctly for size literals.""" config = get_width_config(size) assert config.rem_width == expected_rem assert not config.use_content assert not config.use_stretch assert config.pixel_width == 0 @parameterized.expand( [ ("xxsmall", 0.25), ("xsmall", 0.5), ("small", 0.75), ("medium", 2.5), ("large", 4.25), ("xlarge", 6), ("xxlarge", 8), ] ) def test_get_height_config_rem(self, size: str, expected_rem: float): """get_height_config handles rem values correctly for size literals.""" config = get_height_config(size) assert config.rem_height == expected_rem assert not config.use_content assert not config.use_stretch assert config.pixel_height == 0
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/elements/lib/layout_utils_test.py", "license": "Apache License 2.0", "lines": 318, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/custom_theme_fonts_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_fonts(): """Configure custom theme.""" os.environ["STREAMLIT_THEME_FONT"] = ( # Google Fonts option "Mozilla Headline:https://fonts.googleapis.com/css2?family=Mozilla+Headline&display=swap" ) os.environ["STREAMLIT_THEME_CODE_FONT"] = ( # Adobe Fonts option "playwrite-cc-za:https://use.typekit.net/eor5wum.css" ) os.environ["STREAMLIT_THEME_HEADING_FONT"] = ( # Adobe Fonts option - case-insensitive "FLEGREI:https://use.typekit.net/zru6msp.css" ) os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] = ( "Ojuju:https://fonts.googleapis.com/css2?family=Ojuju:wght@200..800&display=swap" ) os.environ["STREAMLIT_THEME_SIDEBAR_CODE_FONT"] = ( "Rubik Distressed:https://fonts.googleapis.com/css2?family=Rubik+Distressed&display=swap" ) os.environ["STREAMLIT_THEME_SIDEBAR_HEADING_FONT"] = ( "Oswald:https://fonts.googleapis.com/css2?family=Oswald:wght@200..700&display=swap" ) yield del os.environ["STREAMLIT_THEME_FONT"] del os.environ["STREAMLIT_THEME_CODE_FONT"] del os.environ["STREAMLIT_THEME_HEADING_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_CODE_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_HEADING_FONT"] @pytest.mark.usefixtures("configure_custom_fonts") def test_custom_theme(app: Page, assert_snapshot: ImageCompareFunction): # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Add some additional timeout to ensure that fonts can load without # creating flakiness: app.wait_for_timeout(10000) assert_snapshot(app, name="custom_fonts_app", image_threshold=0.0003) @pytest.mark.usefixtures("configure_custom_fonts") def test_custom_theme_main_menu(app: Page, assert_snapshot: ImageCompareFunction): """Test that the main menu is rendered correctly with a custom theme (uses configured font).""" # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Open the main menu app.get_by_test_id("stMainMenu").click() # Replace version with placeholder so snapshots don't change across versions. # The version footer lives outside role="menu" (inside the popover wrapper). popover = app.get_by_test_id("stMainMenuPopover") popover.get_by_text(re.compile(r"^Made with Streamlit v")).evaluate( "el => (el.textContent = 'Made with Streamlit vX.XX.X')" ) assert_snapshot(popover, name="custom_fonts_main_menu")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/custom_theme_fonts_test.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/runtime/theme_util.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING from streamlit.errors import StreamlitAPIException from streamlit.url_util import is_url if TYPE_CHECKING: from streamlit.proto.NewSession_pb2 import CustomThemeConfig def _parse_font_config( font_config: str | None, property_name: str, ) -> tuple[str, str | None]: """Parse a single font configuration string. Args: font_config: The font configuration string (e.g., "Inter" or "Inter:https://...") property_name: The property name for error messages ("font", "codeFont", "headingFont") Returns ------- A tuple of (font_name, source_url). source_url is None if not provided or not valid. """ if not font_config: return "", None # Strip leading/trailing whitespace from the config font_config = font_config.strip() if ":" not in font_config: # No colon found, treat the entire string as the font name return font_config, None # Note: it is possible there are multiple colons in the string, so we need to split on the first colon. font_name, source_url = font_config.split(":", 1) # Strip whitespace from both font name and source font_name = font_name.strip() source_url = source_url.strip() # Check that the href does not contain multiple fonts, so we confirm that "family=" # only shows up once in the source string (structure applies to Google Fonts only) family_occurrences = source_url.count("family=") if family_occurrences > 1: raise StreamlitAPIException( f"The source URL specified in the {property_name} property of config.toml contains multiple fonts. " "Please specify only one font in the source URL." ) is_valid_url = is_url(source_url) # If the source is a valid URL (http/https) but no font name is provided, throw an exception if is_valid_url and not font_name: raise StreamlitAPIException( f"A font family name is required when specifying a source URL " f"for the {property_name} property in config.toml." ) if is_valid_url: return font_name, source_url return font_name, None def _get_font_source_config_name(property_name: str, section: str) -> str: """Get the config name for font sources based on property and section. This is used on the FE as the id for the font source link in the html head. """ if section == "theme": return property_name return f"{property_name}-sidebar" def parse_fonts_with_source( msg: CustomThemeConfig, body_font_config: str | None, code_font_config: str | None, heading_font_config: str | None, section: str, ) -> CustomThemeConfig: """Populate the CustomThemeConfig message with the font, codeFont, and headingFont fields set, as well as the font_sources field to be added to the html head. Args: msg: CustomThemeConfig message to be populated. body_font_config: A string with just the font name (e.g., "Inter") or in the format "<font_family_name_here>:<source_url_here>". code_font_config: A string with just the font name (e.g., "Roboto Mono") or in the format "<code_font_family_name_here>:<source_url_here>". heading_font_config: A string with just the font name (e.g., "Inter Bold") or in the format "<heading_font_family_name_here>:<source_url_here>". section: The section of the config.toml file to parse the fonts from. Examples -------- body_font_config: "Inter" (just font name) code_font_config: "Tagesschrift:https://fonts.googleapis.com/css2?family=Tagesschrift&display=swap" (with source) heading_font_config: "playwrite-cc-za:https://use.typekit.net/xxs7euo.css" Returns ------- Updated CustomThemeConfig message with the font, codeFont, and headingFont fields set. Also sets sources in font_sources field to be added to the html (only when source URLs are provided). """ # Parse body font config body_font_name, body_font_source = _parse_font_config(body_font_config, "font") if body_font_name: msg.body_font = body_font_name if body_font_source: config_name = _get_font_source_config_name("font", section) msg.font_sources.add(config_name=config_name, source_url=body_font_source) # Parse code font config code_font_name, code_font_source = _parse_font_config(code_font_config, "codeFont") if code_font_name: msg.code_font = code_font_name if code_font_source: config_name = _get_font_source_config_name("codeFont", section) msg.font_sources.add(config_name=config_name, source_url=code_font_source) # Parse heading font config heading_font_name, heading_font_source = _parse_font_config( heading_font_config, "headingFont" ) if heading_font_name: msg.heading_font = heading_font_name if heading_font_source: config_name = _get_font_source_config_name("headingFont", section) msg.font_sources.add(config_name=config_name, source_url=heading_font_source) return msg
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/runtime/theme_util.py", "license": "Apache License 2.0", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/runtime/theme_util_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import pytest from streamlit.errors import StreamlitAPIException from streamlit.proto.NewSession_pb2 import CustomThemeConfig from streamlit.runtime.theme_util import parse_fonts_with_source class TestParseFontsWithSource: """Test cases for the parse_fonts_with_source function.""" def test_parse_all_fonts_name_only(self): """Test parsing all three fonts with just font names (no sources).""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config="Inter", code_font_config="Roboto Mono", heading_font_config="Inter Bold", section="theme", ) assert updated_msg.body_font == "Inter" assert updated_msg.code_font == "Roboto Mono" assert updated_msg.heading_font == "Inter Bold" assert len(updated_msg.font_sources) == 0 def test_parse_empty_inputs(self): """Test parsing with empty/None inputs.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config=None, code_font_config=None, heading_font_config=None, section="theme", ) assert updated_msg.body_font == "" assert updated_msg.code_font == "" assert updated_msg.heading_font == "" assert len(updated_msg.font_sources) == 0 def test_parse_body_font_with_source(self): """Test parsing body font with HTTP source URL.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config="Inter:https://fonts.googleapis.com/css2?family=Inter&display=swap", code_font_config=None, heading_font_config=None, section="theme", ) assert updated_msg.body_font == "Inter" assert len(updated_msg.font_sources) == 1 assert updated_msg.font_sources[0].config_name == "font" assert ( updated_msg.font_sources[0].source_url == "https://fonts.googleapis.com/css2?family=Inter&display=swap" ) def test_parse_code_font_with_source(self): """Test parsing code font with HTTPS source URL.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config=None, code_font_config="Tagesschrift:https://fonts.googleapis.com/css2?family=Tagesschrift&display=swap", heading_font_config=None, section="theme", ) assert updated_msg.code_font == "Tagesschrift" assert len(updated_msg.font_sources) == 1 assert updated_msg.font_sources[0].config_name == "codeFont" assert ( updated_msg.font_sources[0].source_url == "https://fonts.googleapis.com/css2?family=Tagesschrift&display=swap" ) def test_parse_heading_font_with_source(self): """Test parsing heading font with HTTP source URL.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config=None, code_font_config=None, heading_font_config="playwrite-cc-za:https://use.typekit.net/eor5wum.css", section="theme", ) assert updated_msg.heading_font == "playwrite-cc-za" assert len(updated_msg.font_sources) == 1 assert updated_msg.font_sources[0].config_name == "headingFont" assert ( updated_msg.font_sources[0].source_url == "https://use.typekit.net/eor5wum.css" ) def test_parse_font_with_empty_name_raises_exception(self): """Test parsing font config with empty name but valid source raises exception.""" msg = CustomThemeConfig() with pytest.raises(StreamlitAPIException) as exc_info: parse_fonts_with_source( msg, body_font_config=":https://fonts.googleapis.com/css2?family=Inter&display=swap", code_font_config=None, heading_font_config=None, section="theme", ) error_message = str(exc_info.value) assert ( "A font family name is required when specifying a source URL for the font property in config.toml." in error_message ) def test_parse_fonts_theme_section(self): """Test parsing fonts with 'theme' section (default config names).""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config="Inter:https://fonts.googleapis.com/css2?family=Inter&display=swap", code_font_config="Roboto:https://fonts.googleapis.com/css2?family=Roboto&display=swap", heading_font_config="Bold:https://fonts.googleapis.com/css2?family=Inter:wght@700&display=swap", section="theme", ) assert len(updated_msg.font_sources) == 3 config_names = [source.config_name for source in updated_msg.font_sources] assert "font" in config_names assert "codeFont" in config_names assert "headingFont" in config_names def test_parse_fonts_theme_sidebar_section(self): """Test parsing fonts with 'theme.sidebar' section (sidebar config names).""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config="Inter:https://fonts.googleapis.com/css2?family=Inter&display=swap", code_font_config="Roboto:https://fonts.googleapis.com/css2?family=Roboto&display=swap", heading_font_config="Bold:https://fonts.googleapis.com/css2?family=Inter:wght@700&display=swap", section="theme.sidebar", ) assert len(updated_msg.font_sources) == 3 config_names = [source.config_name for source in updated_msg.font_sources] assert "font-sidebar" in config_names assert "codeFont-sidebar" in config_names assert "headingFont-sidebar" in config_names def test_mixed_font_configs(self): """Test parsing with mix of font-only and font-with-source configs.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config="Inter", # No source code_font_config="Roboto:https://fonts.googleapis.com/css2?family=Roboto&display=swap", # With source heading_font_config="Bold Font Name", # No source section="theme", ) assert updated_msg.body_font == "Inter" assert updated_msg.code_font == "Roboto" assert updated_msg.heading_font == "Bold Font Name" # Only code font should have a source assert len(updated_msg.font_sources) == 1 assert updated_msg.font_sources[0].config_name == "codeFont" def test_body_font_multiple_families_raises_exception(self): """Test that multiple fonts in body font source raises StreamlitAPIException.""" msg = CustomThemeConfig() with pytest.raises(StreamlitAPIException) as exc_info: parse_fonts_with_source( msg, body_font_config="Inter:https://fonts.googleapis.com/css2?family=Inter&family=Roboto&display=swap", code_font_config=None, heading_font_config=None, section="theme", ) error_message = str(exc_info.value) assert ( "The source URL specified in the font property of config.toml contains multiple fonts. " "Please specify only one font in the source URL." in error_message ) def test_code_font_multiple_families_raises_exception(self): """Test that multiple fonts in code font source raises StreamlitAPIException.""" msg = CustomThemeConfig() with pytest.raises(StreamlitAPIException) as exc_info: parse_fonts_with_source( msg, body_font_config=None, code_font_config="Roboto:https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Source+Code+Pro&display=swap", heading_font_config=None, section="theme", ) error_message = str(exc_info.value) assert ( "The source URL specified in the codeFont property of config.toml contains multiple fonts. " "Please specify only one font in the source URL." in error_message ) def test_heading_font_multiple_families_raises_exception(self): """Test that multiple fonts in heading font source raises StreamlitAPIException.""" msg = CustomThemeConfig() with pytest.raises(StreamlitAPIException) as exc_info: parse_fonts_with_source( msg, body_font_config=None, code_font_config=None, heading_font_config="Bold:https://fonts.googleapis.com/css2?family=Inter:wght@700&family=Roboto:wght@900&display=swap", section="theme", ) error_message = str(exc_info.value) assert ( "The source URL specified in the headingFont property of config.toml contains multiple fonts. " "Please specify only one font in the source URL." in error_message ) def test_parse_font_with_multiple_colons_in_url(self): """Test parsing font config with multiple colons in the source URL.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config="Inter:https://fonts.googleapis.com:443/css2?family=Inter&display=swap", code_font_config=None, heading_font_config=None, section="theme", ) assert updated_msg.body_font == "Inter" assert len(updated_msg.font_sources) == 1 assert ( updated_msg.font_sources[0].source_url == "https://fonts.googleapis.com:443/css2?family=Inter&display=swap" ) def test_parse_font_whitespace_handling(self): """Test parsing font config with whitespace strips whitespace properly.""" msg = CustomThemeConfig() updated_msg = parse_fonts_with_source( msg, body_font_config=" Inter : https://fonts.googleapis.com/css2?family=Inter&display=swap ", code_font_config=None, heading_font_config=None, section="theme", ) # Function should strip whitespace from font name and URL assert updated_msg.body_font == "Inter" assert len(updated_msg.font_sources) == 1 assert ( updated_msg.font_sources[0].source_url == "https://fonts.googleapis.com/css2?family=Inter&display=swap" )
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/runtime/theme_util_test.py", "license": "Apache License 2.0", "lines": 242, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/custom_components/pdf_component.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test app for st.pdf component functionality. This test app includes various PDF component scenarios using st.pdf. Each scenario tests different aspects of the native PDF component. If the component has issues, an exception is shown. """ from __future__ import annotations import base64 import io from typing import TYPE_CHECKING import streamlit as st if TYPE_CHECKING: from collections.abc import Callable # Compact dummy PDF for testing _DUMMY_PDF_CONTENT = ( "%PDF-1.4\n1 0 obj\n<<\n/Type /Catalog\n/Pages 2 0 R\n>>\nendobj\n" "2 0 obj\n<<\n/Type /Pages\n/Kids [3 0 R]\n/Count 1\n>>\nendobj\n" "3 0 obj\n<<\n/Type /Page\n/Parent 2 0 R\n/MediaBox [0 0 612 792]\n" "/Contents 4 0 R\n/Resources <<\n/Font <<\n/F1 5 0 R\n>>\n>>\n>>\nendobj\n" "4 0 obj\n<<\n/Length 44\n>>\nstream\nBT\n/F1 12 Tf\n100 700 Td\n" "(Hello PDF World!) Tj\nET\nendstream\nendobj\n" "5 0 obj\n<<\n/Type /Font\n/Subtype /Type1\n/BaseFont /Helvetica\n>>\nendobj\n" "xref\n0 6\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\n" "0000000115 00000 n\n0000000274 00000 n\n0000000373 00000 n\ntrailer\n" "<<\n/Size 6\n/Root 1 0 R\n>>\nstartxref\n446\n%%EOF" ) def _create_sample_pdf_bytes() -> bytes: """Create a simple PDF as bytes for testing.""" return _DUMMY_PDF_CONTENT.encode("latin-1") def use_st_pdf_basic(): """Test basic st.pdf component usage.""" pdf_bytes = _create_sample_pdf_bytes() st.pdf(pdf_bytes, height=400) def use_st_pdf_file_upload(): """Test st.pdf with file upload functionality.""" uploaded_file = st.file_uploader("Choose a PDF file", type="pdf") if uploaded_file is not None: st.pdf(uploaded_file, height=400) def use_st_pdf_custom_size(): """Test st.pdf with custom height.""" height = st.slider("Select PDF height", min_value=200, max_value=800, value=500) pdf_bytes = _create_sample_pdf_bytes() st.pdf(pdf_bytes, height=height) def use_st_pdf_base64(): """Test st.pdf with base64 encoded data.""" pdf_bytes = _create_sample_pdf_bytes() encoded_pdf = base64.b64encode(pdf_bytes) st.write(f"**Base64 PDF length:** {len(encoded_pdf)} characters") st.code(encoded_pdf[:100].decode() + "...", language="text") decoded_pdf = base64.b64decode(encoded_pdf) st.pdf(decoded_pdf, height=400) def use_st_pdf_bytes_io(): """Test st.pdf with BytesIO object.""" pdf_bytes = _create_sample_pdf_bytes() bytes_io = io.BytesIO(pdf_bytes) st.pdf(bytes_io, height=400) def use_st_pdf_error_handling(): """Test st.pdf error handling with invalid data.""" st.warning("Attempting to display invalid PDF data") # Display invalid PDF data - component handles it gracefully invalid_pdf = b"This is not a valid PDF file" st.pdf(invalid_pdf, height=300) def use_st_pdf_in_columns(): """Test st.pdf in columns layout.""" st.write("**PDFs in Columns Layout**") col1, col2 = st.columns(2) with col1: st.write("**PDF in Column 1**") pdf_bytes = _create_sample_pdf_bytes() st.pdf(pdf_bytes, height=300, key="pdf_column_1") with col2: st.write("**PDF in Column 2**") pdf_bytes = _create_sample_pdf_bytes() st.pdf(pdf_bytes, height=300, key="pdf_column_2") def use_st_pdf_interactive(): """Test interactive PDF features.""" st.markdown("### Interactive PDF Test") # Initialize height in session state if not present if "pdf_height" not in st.session_state: st.session_state.pdf_height = 400 height = st.slider( "Adjust PDF height", min_value=200, max_value=800, value=st.session_state.pdf_height, key="height_slider", ) if st.button("Reset Height"): st.session_state.pdf_height = 400 st.rerun() pdf_bytes = _create_sample_pdf_bytes() st.pdf(pdf_bytes, height=height) options: dict[str, Callable[[], None]] = { "basic": use_st_pdf_basic, "fileUpload": use_st_pdf_file_upload, "customSize": use_st_pdf_custom_size, "base64": use_st_pdf_base64, "bytesIO": use_st_pdf_bytes_io, "errorHandling": use_st_pdf_error_handling, "columns": use_st_pdf_in_columns, "interactive": use_st_pdf_interactive, } st.markdown("# st.pdf Component Tests") st.write("Select a PDF test scenario to run:") st.divider() component_selection = st.selectbox("PDF Test Scenarios", options=options.keys()) if component_selection: st.markdown(f"### Running: {component_selection}") options[component_selection]()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/custom_components/pdf_component.py", "license": "Apache License 2.0", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/custom_components/pdf_component_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test app for st.pdf component functionality and various PDF scenarios.""" import re from playwright.sync_api import Locator, Page, expect from e2e_playwright.conftest import ImageCompareFunction, wait_for_app_run, wait_until from e2e_playwright.shared.app_utils import reset_hovering, select_selectbox_option def _select_pdf_scenario(app: Page, scenario: str): """Select a PDF test scenario from the dropdown.""" select_selectbox_option(app, "PDF Test Scenarios", scenario) # reset hovering to avoid some flakiness: reset_hovering(app) def _expect_pdf_container_attached(app: Page): """Expect the PDF component container to be attached to the DOM.""" pdf_container = app.get_by_test_id("pdf-container") expect(pdf_container).to_be_attached() def _wait_for_slider_to_be_ready(app: Page, timeout: int = 5000): """Wait for the slider to be ready for interaction. Parameters ---------- app : Page The page containing the slider timeout : int Maximum time to wait in milliseconds """ slider = app.get_by_test_id("stSlider") if slider.count() > 0: # If there's a slider on the page, wait for it to be ready expect(slider).to_be_visible(timeout=timeout) expect(slider.get_by_role("slider")).to_be_enabled(timeout=timeout) def _wait_for_pdf_to_load( app: Page, timeout: int = 15000, pdf_container: Locator | None = None ): """Wait for PDF content to finish loading inside the DOM container. The PDF component renders directly in the DOM (no iframe) and exposes a container with data-testid="pdf-container". Parameters ---------- app : Page The page containing the PDF component timeout : int Maximum time to wait in milliseconds pdf_container : Locator | None Optional locator for a specific PDF container. If not provided, the default container test id is used. """ if pdf_container is None: pdf_container = app.get_by_test_id("pdf-container") # First ensure the container is attached and visible expect(pdf_container).to_be_visible(timeout=timeout) # While loading, the component may render an element with data-testid="pdf-loading". # We wait for that loading indicator to be hidden or gone. loading_indicator = pdf_container.get_by_test_id("pdf-loading") expect(loading_indicator).to_be_hidden(timeout=timeout) # Wait for the first page to actually render in the DOM. # The PDF component uses a virtualized list with data-index attributes for pages. first_page = pdf_container.locator('[data-index="0"]') expect(first_page).to_be_visible(timeout=timeout) def test_st_pdf_basic_functionality(app: Page, assert_snapshot: ImageCompareFunction): """Test basic st.pdf component functionality with snapshot.""" _select_pdf_scenario(app, "basic") _expect_pdf_container_attached(app) # Wait for PDF to be fully loaded before taking snapshot _wait_for_pdf_to_load(app) pdf_container = app.get_by_test_id("pdf-container") assert_snapshot(pdf_container, name="st_pdf-basic_functionality") def test_st_pdf_file_upload_no_file(app: Page, assert_snapshot: ImageCompareFunction): """Test st.pdf with file upload when no file is uploaded.""" _select_pdf_scenario(app, "fileUpload") file_uploader = app.get_by_test_id("stFileUploader") expect(file_uploader).to_be_visible() # Should not display any PDF when no file is uploaded expect(app.get_by_test_id("pdf-container")).not_to_be_attached() # Take snapshot of just the file uploader state file_uploader = app.get_by_test_id("stFileUploader") assert_snapshot(file_uploader, name="st_pdf-file_upload_no_file") def test_st_pdf_custom_size(app: Page, assert_snapshot: ImageCompareFunction): """Test st.pdf with custom height.""" _select_pdf_scenario(app, "customSize") height_slider = app.get_by_test_id("stSlider") expect(height_slider).to_be_visible() # Wait for slider to be ready for interaction _wait_for_slider_to_be_ready(app) _expect_pdf_container_attached(app) # Wait for PDF to be fully loaded _wait_for_pdf_to_load(app) # Capture just the PDF container to focus on the height setting pdf_container = app.get_by_test_id("pdf-container") assert_snapshot(pdf_container, name="st_pdf-custom_size") def test_st_pdf_base64_encoding(app: Page, assert_snapshot: ImageCompareFunction): """Test st.pdf with base64 encoded data.""" _select_pdf_scenario(app, "base64") base64_info = app.get_by_test_id("stMarkdown").filter(has_text="Base64 PDF length:") expect(base64_info).to_be_visible() code_block = app.get_by_test_id("stCode") expect(code_block).to_be_visible() _expect_pdf_container_attached(app) # Wait for PDF to be fully loaded _wait_for_pdf_to_load(app) # Take snapshot of just the PDF container, following the good example from bytes_io test pdf_container = app.get_by_test_id("pdf-container") assert_snapshot(pdf_container, name="st_pdf-base64_encoding") def test_st_pdf_bytes_io(app: Page, assert_snapshot: ImageCompareFunction): """Test st.pdf with BytesIO object.""" _select_pdf_scenario(app, "bytesIO") _expect_pdf_container_attached(app) # Wait for PDF to be fully loaded before taking snapshot _wait_for_pdf_to_load(app) pdf_container = app.get_by_test_id("pdf-container") assert_snapshot(pdf_container, name="st_pdf-bytes_io") def test_st_pdf_error_handling(app: Page, assert_snapshot: ImageCompareFunction): """Test st.pdf error handling with invalid data.""" _select_pdf_scenario(app, "errorHandling") warning_message = app.get_by_test_id("stAlert").filter( has_text="Attempting to display invalid PDF data" ) expect(warning_message).to_be_visible() # Even with invalid data, the component should still render the PDF container pdf_container = app.get_by_test_id("pdf-container") expect(pdf_container).to_be_visible() # Capture just the warning message - the error state in the PDF viewer isn't visually meaningful warning_message = app.get_by_test_id("stAlert") assert_snapshot(warning_message, name="st_pdf-error_handling") def test_st_pdf_in_columns(app: Page, assert_snapshot: ImageCompareFunction): """Test st.pdf in columns layout.""" _select_pdf_scenario(app, "columns") description = app.get_by_test_id("stMarkdown").filter( has_text="PDFs in Columns Layout" ) expect(description).to_be_visible() col1_header = app.get_by_test_id("stMarkdown").filter(has_text="PDF in Column 1") col2_header = app.get_by_test_id("stMarkdown").filter(has_text="PDF in Column 2") expect(col1_header).to_be_visible() expect(col2_header).to_be_visible() # Verify multiple PDFs are rendered in columns pdf_containers = app.get_by_test_id("pdf-container") expect(pdf_containers).to_have_count(2) # Wait for both containers to be visible first_container = pdf_containers.nth(0) second_container = pdf_containers.nth(1) expect(first_container).to_be_visible() expect(second_container).to_be_visible() # Wait for both PDFs to load _wait_for_pdf_to_load(app, pdf_container=first_container) _wait_for_pdf_to_load(app, pdf_container=second_container) # Take snapshot focusing on the column layout with PDFs columns_container = app.get_by_test_id("stHorizontalBlock") assert_snapshot(columns_container, name="st_pdf-in_columns") def test_st_pdf_interactive(app: Page, assert_snapshot: ImageCompareFunction): """Test interactive PDF features.""" _select_pdf_scenario(app, "interactive") subheader = app.get_by_test_id("stMarkdown").filter(has_text="Interactive PDF Test") expect(subheader).to_be_visible() height_slider = app.get_by_test_id("stSlider") expect(height_slider).to_be_visible() # Wait for slider to be ready for interaction _wait_for_slider_to_be_ready(app) reset_button = app.get_by_test_id("stButton").filter(has_text="Reset Height") expect(reset_button).to_be_visible() _expect_pdf_container_attached(app) # Wait for PDF to be fully loaded _wait_for_pdf_to_load(app) # Take snapshot of just the PDF container in initial state pdf_container = app.get_by_test_id("pdf-container") assert_snapshot(pdf_container, name="st_pdf-interactive_initial") # Test that the reset button actually works reset_button.click() wait_for_app_run(app) # After reset, the PDF should still be visible _expect_pdf_container_attached(app) # Wait for PDF to load again after reset _wait_for_pdf_to_load(app) # Take snapshot after reset to verify state assert_snapshot(pdf_container, name="st_pdf-interactive_after_reset") def test_st_pdf_app_title_and_selection(app: Page): """Test that the app title and selection dropdown work correctly.""" title = app.get_by_test_id("stMarkdown").filter(has_text="st.pdf Component Tests") expect(title).to_be_visible() description = app.get_by_test_id("stMarkdown").filter( has_text="Select a PDF test scenario to run:" ) expect(description).to_be_visible() selectbox = app.get_by_test_id("stSelectbox") expect(selectbox).to_be_visible() scenarios = [ "basic", "fileUpload", "customSize", ] for scenario in scenarios: _select_pdf_scenario(app, scenario) subheader = app.get_by_test_id("stMarkdown").filter( has_text=f"Running: {scenario}" ) expect(subheader).to_be_visible() def test_st_pdf_component_container_behavior(app: Page): """Test that st.pdf component creates a proper DOM container.""" _select_pdf_scenario(app, "basic") pdf_container = app.get_by_test_id("pdf-container") expect(pdf_container).to_be_attached() expect(pdf_container).to_be_visible() def test_st_pdf_widget_interactions(app: Page): """Test interactions with st.pdf widget controls.""" _select_pdf_scenario(app, "customSize") height_slider = app.get_by_test_id("stSlider") expect(height_slider).to_be_visible() # Wait for slider to be ready for interaction _wait_for_slider_to_be_ready(app) slider_thumb = height_slider.locator("[role='slider']") expect(slider_thumb).to_be_visible() expect(slider_thumb).to_have_attribute("aria-valuenow", re.compile(r".*")) # Verify that the PDF renders with the current slider value _expect_pdf_container_attached(app) def test_st_pdf_different_heights_snapshots( app: Page, assert_snapshot: ImageCompareFunction ): """Test PDF component with different height values for visual comparison.""" # Set a taller viewport to accommodate the maximum PDF height (800px) app.set_viewport_size({"width": 1280, "height": 1000}) _select_pdf_scenario(app, "customSize") height_slider = app.get_by_test_id("stSlider") expect(height_slider).to_be_visible() # Wait for slider to be ready for interaction _wait_for_slider_to_be_ready(app) # Wait for initial PDF to load _expect_pdf_container_attached(app) _wait_for_pdf_to_load(app, timeout=30000) pdf_container = app.get_by_test_id("pdf-container") # Record initial height and take snapshot at default height (500px) initial_box = pdf_container.bounding_box() assert initial_box is not None initial_height = initial_box["height"] assert_snapshot(pdf_container, name="st_pdf-height_default") # Get the actual slider element slider_element = height_slider.get_by_role("slider") expect(slider_element).to_be_visible() # Move slider to minimum (200px) using proper e2e slider interaction slider_element.hover() app.mouse.down() # Move mouse far to the left to reach minimum value app.mouse.move(0, 0) # Move to far left of screen app.mouse.up() wait_for_app_run(app) # Wait for PDF to adjust to new height and fully load _wait_for_pdf_to_load(app, timeout=30000) # Verify we actually reached a noticeably lower height than the initial one def _is_min_height_reached() -> bool: box = pdf_container.bounding_box() return box is not None and box["height"] < initial_height - 10 wait_until(app, _is_min_height_reached, timeout=7000) min_box = pdf_container.bounding_box() assert min_box is not None min_height = min_box["height"] assert_snapshot(pdf_container, name="st_pdf-height_minimum") # Move slider to maximum (800px) using proper e2e slider interaction slider_element.hover() app.mouse.down() # Move mouse far to the right to reach maximum value app.mouse.move(1000, 0) # Move to far right of screen app.mouse.up() wait_for_app_run(app) # Wait for PDF to adjust to new height and fully load _wait_for_pdf_to_load(app, timeout=30000) # Verify we actually reached a higher height than the minimum one def _is_max_height_reached() -> bool: box = pdf_container.bounding_box() return box is not None and box["height"] > min_height + 10 wait_until(app, _is_max_height_reached, timeout=7000) assert_snapshot(pdf_container, name="st_pdf-height_maximum")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/custom_components/pdf_component_test.py", "license": "Apache License 2.0", "lines": 280, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:lib/streamlit/elements/pdf.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import io from pathlib import Path from typing import TYPE_CHECKING, Any, TypeAlias, cast from streamlit import url_util from streamlit.elements.lib.layout_utils import validate_height from streamlit.errors import StreamlitAPIException from streamlit.runtime.metrics_util import gather_metrics if TYPE_CHECKING: from streamlit.delta_generator import DeltaGenerator from streamlit.elements.lib.layout_utils import HeightWithoutContent PdfData: TypeAlias = str | Path | bytes | io.BytesIO def _get_pdf_component() -> Any | None: """Get the PDF custom component if available. Returns ------- Any | None The pdf_viewer function if the streamlit-pdf component is available, None otherwise. """ try: import streamlit_pdf # type: ignore return streamlit_pdf.pdf_viewer except ImportError: return None class PdfMixin: @gather_metrics("pdf") def pdf( self, data: PdfData, *, height: HeightWithoutContent = 500, key: str | None = None, ) -> DeltaGenerator: """Display a PDF viewer. .. Important:: You must install |streamlit-pdf|_ to use this command. You can install it as an extra with Streamlit: .. code-block:: shell pip install streamlit[pdf] .. |streamlit-pdf| replace:: ``streamlit-pdf`` .. _streamlit-pdf: https://github.com/streamlit/streamlit-pdf Parameters ---------- data : str, Path, BytesIO, or bytes The PDF file to show. This can be one of the following: - A URL (string) for a hosted PDF file. - A path to a local PDF file. If you use a relative path, it must be relative to the current working directory. - A file-like object. For example, this can be an ``UploadedFile`` from ``st.file_uploader``, or this can be a local file opened with ``open()``. - Raw bytes data. height : int or "stretch" The height of the PDF viewer. This can be one of the following: - An integer specifying the height in pixels: The viewer has a fixed height. If the content is larger than the specified height, scrolling is enabled. This is ``500`` by default. - ``"stretch"``: The height of the viewer matches the height of its content or the height of the parent container, whichever is larger. If the viewer is not in a parent container, the height of the viewer matches the height of its content. Example ------- >>> st.pdf("https://example.com/sample.pdf") >>> st.pdf("https://example.com/sample.pdf", height=600) """ # Validate data parameter early if data is None: raise StreamlitAPIException( "The PDF data cannot be None. Please provide a valid PDF file path, URL, " "bytes data, or file-like object." ) # Check if custom PDF component is available first pdf_component = _get_pdf_component() if pdf_component is None: return self._show_pdf_warning() return self._call_pdf_component(pdf_component, data, height, key) def _call_pdf_component( self, pdf_component: Any, data: PdfData, height: HeightWithoutContent, key: str | None, ) -> DeltaGenerator: """Call the custom PDF component with the provided data.""" # Validate height parameter after confirming component is available validate_height(height, allow_content=False) # Convert data to the format expected by pdf_viewer component file_param: str | bytes if isinstance(data, (str, Path)): data_str = str(data).strip() # Strip whitespace from URLs if url_util.is_url(data_str, allowed_schemas=("http", "https")): # It's a URL - pass directly file_param = data_str else: # It's a local file path - read the content as bytes for security try: with open(data_str, "rb") as file: file_param = file.read() except (FileNotFoundError, PermissionError) as e: raise StreamlitAPIException( f"Unable to read file '{data_str}': {e}" ) elif isinstance(data, bytes): # Pass bytes directly - the component will handle uploading to media storage file_param = data elif hasattr(data, "read") and hasattr(data, "getvalue"): # Handle BytesIO and similar file_param = data.getvalue() elif hasattr(data, "read"): # Handle other file-like objects file_param = data.read() else: # Provide a more helpful error message raise StreamlitAPIException( f"Unsupported data type for PDF: {type(data).__name__}. " f"Please provide a file path (str or Path), URL (str), bytes data, " f"or file-like object (such as BytesIO or UploadedFile)." ) # Convert to component-compatible format if height == "stretch": # For stretch, we need to pass a special value the component understands # This maintains compatibility with the component while using standard layout component_height = "stretch" else: component_height = str(height) result = pdf_component( file=file_param, height=component_height, key=key, ) return cast("DeltaGenerator", result) def _show_pdf_warning(self) -> DeltaGenerator: """Raise an exception that the PDF component is not available.""" raise StreamlitAPIException( "The PDF viewer requires the `streamlit-pdf` component to be installed.\n\n" "Please run `pip install streamlit[pdf]` to install it.\n\n" "For more information, see the Streamlit PDF documentation at " "https://docs.streamlit.io/develop/api-reference/media/st.pdf." # TODO: Update this URL when docs are updated ) @property def dg(self) -> DeltaGenerator: """Get our DeltaGenerator.""" return cast("DeltaGenerator", self)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/streamlit/elements/pdf.py", "license": "Apache License 2.0", "lines": 159, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/elements/pdf_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PDF element unit test.""" import io import json from pathlib import Path from unittest.mock import patch import pytest from parameterized import parameterized import streamlit as st from streamlit.errors import StreamlitAPIException from tests.delta_generator_test_case import DeltaGeneratorTestCase class PdfComponentAvailabilityTest(DeltaGeneratorTestCase): """Test the PDF component availability check.""" def test_pdf_component_not_available(self): """Test when PDF component is not available.""" # Import the module so we can access the function through it from streamlit.elements import pdf as pdf_module with patch.object(pdf_module, "_get_pdf_component", return_value=None): assert pdf_module._get_pdf_component() is None def test_pdf_component_import_error(self): """Test when PDF component import fails - checking behavior.""" # Simply test that st.pdf raises the appropriate error when component is not available with patch("streamlit.elements.pdf._get_pdf_component", return_value=None): with pytest.raises(StreamlitAPIException) as exc_info: st.pdf(b"dummy pdf data") assert "streamlit[pdf]" in str(exc_info.value) assert "pip install" in str(exc_info.value) def test_pdf_raises_when_component_not_available(self): """Test that st.pdf raises an appropriate error when component is not available.""" with patch("streamlit.elements.pdf._get_pdf_component", return_value=None): with pytest.raises(StreamlitAPIException) as exc_info: st.pdf("https://example.com/fake.pdf") assert "streamlit[pdf]" in str(exc_info.value) assert "pip install streamlit[pdf]" in str(exc_info.value) class PdfTest(DeltaGeneratorTestCase): """Test ability to marshall PDF protos.""" # Dummy PDF bytes for testing (not a real PDF, but sufficient for testing) DUMMY_PDF_BYTES = ( b"%PDF-1.4\n1 0 obj\n<<\n/Type /Catalog\n>>\nendobj\nxref\n0 1\n0000000000 65535" b"f \ntrailer\n<<\n/Size 1\n/Root 1 0 R\n>>\nstartxref\n9\n%%EOF" ) def test_pdf_url(self): """Test PDF with URL.""" # Use a fake URL to avoid dependency on external resources url = "https://example.com/fake-document.pdf" st.pdf(url) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" # Parse the JSON args to check the parameters json_args = json.loads(element.bidi_component.json) assert json_args["file"] == url assert json_args["height"] == "500" # Height is converted to string def test_pdf_with_height(self): """Test PDF with custom height.""" url = "https://example.com/fake-document.pdf" st.pdf(url, height=600) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" json_args = json.loads(element.bidi_component.json) assert json_args["file"] == url assert json_args["height"] == "600" # Height is converted to string def test_pdf_with_height_stretch(self): """Test PDF with stretch height.""" url = "https://example.com/fake-document.pdf" st.pdf(url, height="stretch") element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" json_args = json.loads(element.bidi_component.json) assert json_args["file"] == url assert ( json_args["height"] == "stretch" ) # stretch is passed as "stretch" to component def test_pdf_with_bytes_data(self): """Test PDF with raw bytes data.""" st.pdf(self.DUMMY_PDF_BYTES) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" # Check that bytes are uploaded to media storage and passed as URL json_args = json.loads(element.bidi_component.json) assert json_args["file"].startswith("/media/") # Media URL assert json_args["height"] == "500" def test_pdf_with_bytesio_data(self): """Test PDF with BytesIO data.""" pdf_bytesio = io.BytesIO(self.DUMMY_PDF_BYTES) st.pdf(pdf_bytesio) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" # Check that bytes are uploaded to media storage and passed as URL json_args = json.loads(element.bidi_component.json) assert json_args["file"].startswith("/media/") # Media URL assert json_args["height"] == "500" def test_pdf_with_file_like_object(self): """Test PDF with file-like object (simulating UploadedFile).""" # Create a mock file-like object class MockUploadedFile: def __init__(self, data): self._data = data def read(self): return self._data mock_file = MockUploadedFile(self.DUMMY_PDF_BYTES) st.pdf(mock_file) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" # Check that bytes are uploaded to media storage and passed as URL json_args = json.loads(element.bidi_component.json) assert json_args["file"].startswith("/media/") # Media URL assert json_args["height"] == "500" def test_pdf_with_path_object(self): """Test PDF with Path object.""" # Create a temporary file to test with import os import tempfile with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_file: tmp_file.write(self.DUMMY_PDF_BYTES) tmp_file_path = tmp_file.name try: path_obj = Path(tmp_file_path) st.pdf(path_obj) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" json_args = json.loads(element.bidi_component.json) # For file paths, the content is uploaded to media storage assert json_args["file"].startswith("/media/") # Media URL assert json_args["height"] == "500" finally: # Clean up the temporary file os.unlink(tmp_file_path) def test_pdf_with_local_file_path_string(self): """Test PDF with local file path as string.""" # Create a temporary file to test with import os import tempfile with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_file: tmp_file.write(self.DUMMY_PDF_BYTES) tmp_file_path = tmp_file.name try: st.pdf(tmp_file_path) element = self.get_delta_from_queue().new_element assert element.bidi_component.component_name == "streamlit-pdf.pdf_viewer" json_args = json.loads(element.bidi_component.json) # For file paths, the content is uploaded to media storage assert json_args["file"].startswith("/media/") # Media URL assert json_args["height"] == "500" finally: # Clean up the temporary file os.unlink(tmp_file_path) def test_pdf_with_invalid_file_path(self): """Test PDF with invalid file path.""" invalid_path = "/nonexistent/path/to/file.pdf" with pytest.raises( StreamlitAPIException, match=f"Unable to read file '{invalid_path}'" ): st.pdf(invalid_path) def test_pdf_with_none_data(self): """Test PDF with None data.""" with pytest.raises(StreamlitAPIException, match="The PDF data cannot be None"): st.pdf(None) def test_pdf_with_unsupported_data_type(self): """Test PDF with unsupported data type.""" unsupported_data = {"not": "supported"} with pytest.raises( StreamlitAPIException, match="Unsupported data type for PDF" ): st.pdf(unsupported_data) @parameterized.expand( [ "invalid", "content", # content is not allowed for PDF -100, 0, 100.5, ] ) def test_pdf_with_invalid_height(self, height): """Test PDF with invalid height values.""" url = "https://example.com/fake-document.pdf" with pytest.raises(StreamlitAPIException) as e: st.pdf(url, height=height) assert "Invalid height" in str(e.value) def test_pdf_height_as_integer_gets_stringified(self): """Test that integer height values are converted to strings for the component.""" url = "https://example.com/fake-document.pdf" st.pdf(url, height=450) element = self.get_delta_from_queue().new_element json_args = json.loads(element.bidi_component.json) # Component should receive height as string assert json_args["height"] == "450" assert isinstance(json_args["height"], str)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/elements/pdf_test.py", "license": "Apache License 2.0", "lines": 200, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/shared/theme_utils.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for flexible theme configuration in e2e tests.""" from __future__ import annotations import json from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from playwright.sync_api import Page def apply_theme_via_window( page: Page, base: str = "light", **theme_options: Any ) -> None: """Apply custom theme via window.__streamlit injection. This approach works per-test and doesn't require environment variable isolation. Args: page: Playwright Page object base: Base theme to use ('light' or 'dark') **theme_options: Theme configuration options (e.g., textColor, backgroundColor, etc.) Example: apply_theme_via_window( page, base="light", textColor="#301934", backgroundColor="#CBC3E3" ) """ theme_key = "LIGHT_THEME" if base == "light" else "DARK_THEME" # Build theme configuration theme_config = {"base": base} theme_config.update(theme_options) # Inject theme configuration into window.__streamlit page.add_init_script(f""" window.__streamlit = {{ {theme_key}: {json.dumps(theme_config)} }} """)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/shared/theme_utils.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/shared/vega_utils.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from playwright.sync_api._generated import Locator def assert_vega_chart_height( vega_chart: Locator, expected_height: int, description: str | None = None, tolerance: int = 0, ): vega_graphics_doc = vega_chart.locator("[role='graphics-document']") bbox = vega_graphics_doc.bounding_box() chart_info = f" ({description})" if description else "" assert bbox is not None, f"Vega chart{chart_info} has no bounding box" actual_height = round(bbox["height"]) height_diff = abs(actual_height - expected_height) assert height_diff <= tolerance, ( f"Vega chart{chart_info} height mismatch: " f"expected {expected_height}px, got {actual_height}px " f"(diff: {actual_height - expected_height}px, tolerance: {tolerance}px)" ) def assert_vega_chart_width( vega_chart: Locator, expected_width: int, description: str | None = None, tolerance: int = 0, ): vega_graphics_doc = vega_chart.locator("[role='graphics-document']") bbox = vega_graphics_doc.bounding_box() chart_info = f" ({description})" if description else "" assert bbox is not None, f"Vega chart{chart_info} has no bounding box" actual_width = round(bbox["width"]) width_diff = abs(actual_width - expected_width) assert width_diff <= tolerance, ( f"Vega chart{chart_info} width mismatch: " f"expected {expected_width}px, got {actual_width}px " f"(diff: {actual_width - expected_width}px, tolerance: {tolerance}px)" )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/shared/vega_utils.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_alignment.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import numpy as np import numpy.typing as npt import pandas as pd import streamlit as st with st.container( horizontal=True, border=True, horizontal_alignment="left", key="container-horizontal-align-left", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal=True, border=True, horizontal_alignment="center", key="container-horizontal-align-center", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal=True, border=True, horizontal_alignment="right", key="container-horizontal-align-right", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal=True, border=True, horizontal_alignment="distribute", key="container-horizontal-align-distribute", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal=True, border=True, vertical_alignment="top", key="container-horizontal-vertical-align-top", ): st.container(border=True, height=70) st.container(border=True, height=125) st.container(border=True, height=25) with st.container( horizontal=True, border=True, vertical_alignment="center", key="container-horizontal-vertical-align-center", ): st.container(border=True, height=70) st.container(border=True, height=125) st.container(border=True, height=25) with st.container( horizontal=True, border=True, vertical_alignment="bottom", key="container-horizontal-vertical-align-bottom", ): st.container(border=True, height=70) st.container(border=True, height=125) st.container(border=True, height=25) with st.container( horizontal=False, border=True, vertical_alignment="top", height=300, key="container-vertical-vertical-align-top", ): st.html('<div style="background:lightblue;">One</div>') st.html('<div style="background:lightblue;">Two</div>') st.html('<div style="background:lightblue;">Three</div>') with st.container( horizontal=False, border=True, vertical_alignment="center", height=300, key="container-vertical-vertical-align-center", ): st.html('<div style="background:lightblue;">One</div>') st.html('<div style="background:lightblue;">Two</div>') st.html('<div style="background:lightblue;">Three</div>') with st.container( horizontal=False, border=True, vertical_alignment="bottom", height=300, key="container-vertical-vertical-align-bottom", ): st.html('<div style="background:lightblue;">One</div>') st.html('<div style="background:lightblue;">Two</div>') st.html('<div style="background:lightblue;">Three</div>') with st.container( horizontal=False, border=True, vertical_alignment="distribute", height=300, key="container-vertical-vertical-align-distribute", ): st.html('<div style="background:lightblue;">One</div>') st.html('<div style="background:lightblue;">Two</div>') st.html('<div style="background:lightblue;">Three</div>') with st.container( horizontal=False, border=True, horizontal_alignment="left", key="container-vertical-horizontal-align-left", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal=False, border=True, horizontal_alignment="center", key="container-vertical-horizontal-align-center", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal=False, border=True, horizontal_alignment="right", key="container-vertical-horizontal-align-right", ): st.html('<div style="background:lightblue;">One</div>', width="content") st.html('<div style="background:lightblue;">Two</div>', width="content") st.html('<div style="background:lightblue;">Three</div>', width="content") with st.container( horizontal_alignment="center", key="container-horizontal-centered-elements", border=True, ): df = pd.DataFrame( { "x": list(range(3)), "y": [i * i for i in range(3)], } ) img: npt.NDArray[np.int64] = np.repeat(0, 2500).reshape(50, 50) st.image(img) st.dataframe( df, width="content", ) st.bar_chart(df, x="x", y="y", width="content")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_alignment.py", "license": "Apache License 2.0", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_alignment_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import get_element_by_key CONTAINER_KEYS = [ "container-horizontal-align-left", "container-horizontal-align-center", "container-horizontal-align-right", "container-horizontal-align-distribute", "container-horizontal-vertical-align-top", "container-horizontal-vertical-align-center", "container-horizontal-vertical-align-bottom", "container-vertical-vertical-align-top", "container-vertical-vertical-align-center", "container-vertical-vertical-align-bottom", "container-vertical-vertical-align-distribute", "container-vertical-horizontal-align-left", "container-vertical-horizontal-align-center", "container-vertical-horizontal-align-right", "container-horizontal-centered-elements", ] def test_layouts_container_alignment(app: Page, assert_snapshot: ImageCompareFunction): """Snapshot test for each top-level container in st_layouts_container_alignment.py.""" for key in CONTAINER_KEYS: locator = get_element_by_key(app, key) assert_snapshot(locator, name=f"st_layouts_container_alignment-{key}")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_alignment_test.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_layouts_container_directions.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import streamlit as st with st.container( horizontal=True, border=True, key="container-horizontal-basic", ): st.html( '<div style="background:lightblue">Hello</div>', width=300, ) st.html( '<div style="background:lightblue">World</div>', width=300, ) with st.container(horizontal=False, border=True, key="container-vertical-basic"): st.html( '<div style="background:lightblue">Hello</div>', width="stretch", ) st.html( '<div style="background:lightblue">World</div>', width="stretch", ) # # Horizontal layout with a fixed-width element with st.container( horizontal=True, border=True, key="container-horizontal-fixed-width-and-stretch-element", ): st.html( '<div style="background:lightyellow">Fixed width element (400px)</div>', width=400, ) st.html( '<div style="background:lightblue">Stretch width element</div>', width="stretch", ) # Horizontal layout with a fixed-height element with st.container( horizontal=True, border=True, key="container-horizontal-fixed-height-element", ): with st.container(height=500, border=True): st.write("Fixed 500px height container") with st.container(border=True): st.write("Default height container") # Vertical layout with a fixed-width element with st.container( horizontal=False, key="container-vertical-fixed-width-and-stretch-element", border=True, ): st.html( '<div style="background:lightyellow">Fixed width element (500px)</div>', width=500, ) st.html( '<div style="background:lightblue">Stretch width element</div>', width="stretch", ) # Vertical layout with a fixed-height element with st.container( horizontal=False, border=True, key="container-vertical-fixed-height-element" ): with st.container(height=500, border=True): st.write("Fixed 500px height container") with st.container(border=True): st.write("Default height container")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_directions.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_directions_fullscreen_elements.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import streamlit as st with st.container(horizontal=True, border=True): st.html('<div style="background:lightblue; padding:8px;">Left text</div>') st.vega_lite_chart( { "data": {"values": [{"x": i, "y": i * i} for i in range(5)]}, "mark": "line", "encoding": {"x": {"field": "x"}, "y": {"field": "y"}}, } ) st.html('<div style="background:lightblue; padding:8px;">Right text</div>') with st.container(horizontal=True, border=True): st.html('<div style="background:lightgreen;">Left panel</div>') st.dataframe({"A": [1, 2, 3], "B": [4, 5, 6]})
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_directions_fullscreen_elements.py", "license": "Apache License 2.0", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_directions_fullscreen_elements_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction, wait_for_app_run from e2e_playwright.shared.toolbar_utils import ( assert_fullscreen_toolbar_button_interactions, ) def test_vega_lite_chart_fullscreen(app: Page, assert_snapshot: ImageCompareFunction): """Test fullscreen open/close for the vega_lite_chart in the first container.""" wait_for_app_run(app) expect(app.get_by_test_id("stVegaLiteChart")).to_have_count(1) widget_element = app.get_by_test_id("stVegaLiteChart").first widget_toolbar = widget_element.locator("..").get_by_test_id("stElementToolbar") fullscreen_wrapper = app.get_by_test_id("stFullScreenFrame").first fullscreen_toolbar_button = widget_toolbar.get_by_test_id( "stElementToolbarButton" ).last widget_element.hover() expect(widget_toolbar).to_have_css("opacity", "1") assert_snapshot( widget_element, name="st_layouts_container_directions_fullscreen_elements-vega_lite_chart-normal", ) fullscreen_toolbar_button.click() expect( widget_toolbar.get_by_role("button", name="Close fullscreen") ).to_be_visible() assert_snapshot( app, name="st_layouts_container_directions_fullscreen_elements-vega_lite_chart-fullscreen_expanded", ) fullscreen_toolbar_button.click() expect(widget_toolbar.get_by_role("button", name="Fullscreen")).to_be_visible() assert_snapshot( fullscreen_wrapper, name="st_layouts_container_directions_fullscreen_elements-vega_lite_chart-fullscreen_collapsed", ) def test_dataframe_fullscreen(app: Page, assert_snapshot: ImageCompareFunction): """Test fullscreen open/close for the dataframe in the second container.""" wait_for_app_run(app) expect(app.get_by_test_id("stDataFrame")).to_have_count(1) assert_fullscreen_toolbar_button_interactions( app, assert_snapshot=assert_snapshot, widget_test_id="stDataFrame", filename_prefix="st_layouts_container_directions_fullscreen_elements-dataframe", nth=0, fullscreen_wrapper_nth=1, )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_directions_fullscreen_elements_test.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_layouts_container_directions_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import get_element_by_key CONTAINER_KEYS = [ "container-horizontal-basic", "container-vertical-basic", "container-horizontal-fixed-width-and-stretch-element", "container-horizontal-fixed-height-element", "container-vertical-fixed-width-and-stretch-element", "container-vertical-fixed-height-element", ] def test_layouts_container_directions(app: Page, assert_snapshot: ImageCompareFunction): """Snapshot test for each top-level container in st_layouts_container_directions.py.""" for key in CONTAINER_KEYS: locator = get_element_by_key(app, key) assert_snapshot(locator, name=f"st_layouts_container_directions-{key}")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_directions_test.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_layouts_container_gap_size.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, cast import streamlit as st if TYPE_CHECKING: from streamlit.elements.lib.layout_utils import Gap GAPS = cast( "list[Gap | None]", [ None, "xxsmall", "xsmall", "small", "medium", "large", "xlarge", "xxlarge", ], ) for gap in GAPS: gap_name = str(gap).lower() with st.container( border=True, gap=gap, horizontal=True, key=f"container-horizontal-gap-{gap_name}", ): st.html( '<div style="background:lightblue">One</div>', width="stretch", ) st.html( '<div style="background:lightblue">Two</div>', width="stretch", ) st.html( '<div style="background:lightblue">Three</div>', width="stretch", ) st.html( '<div style="background:lightblue">Four</div>', width="stretch", ) for gap in GAPS: gap_name = str(gap).lower() with st.container( border=True, gap=gap, horizontal=False, key=f"container-vertical-gap-{gap_name}", ): st.html( '<div style="background:lightblue">One</div>', width="stretch", ) st.html( '<div style="background:lightblue">Two</div>', width="stretch", ) st.html( '<div style="background:lightblue">Three</div>', width="stretch", )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_gap_size.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_gap_size_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import get_element_by_key GAPS = [ None, "xxsmall", "xsmall", "small", "medium", "large", "xlarge", "xxlarge", ] def test_layouts_container_gap_size(app: Page, assert_snapshot: ImageCompareFunction): """Snapshot test for each top-level container in st_layouts_container_gap_size.py.""" for gap in GAPS: gap_name = str(gap).lower() container_keys = [ f"container-horizontal-gap-{gap_name}", f"container-vertical-gap-{gap_name}", ] for key in container_keys: locator = get_element_by_key(app, key) assert_snapshot(locator, name=f"st_layouts_container_gap_size-{key}")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_gap_size_test.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_layouts_container_min_width.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import date import pandas as pd import streamlit as st with st.container(horizontal=True, border=True, key="layout-horizontal-markdown"): st.markdown("Hello", width="stretch") st.markdown("Hello", width="stretch") st.markdown( "Really long test. Reallly long text. Really long text. This is a really long text. This is really long text.", width="stretch", ) st.markdown("Hello", width="stretch") st.markdown("Hello", width="stretch") st.markdown( "Really long test. Reallly long text. Really long text.", width="stretch" ) st.markdown("Hello", width="stretch") st.markdown("Hello", width="stretch") st.markdown( "Really long test. Reallly long text. Really long text.", width="stretch" ) st.markdown("Hello", width="stretch") st.markdown("Hello", width="stretch") st.markdown("Hello", width="stretch") with st.container(horizontal=True, border=True, key="layout-horizontal-buttons"): st.button("A", width="stretch") st.button("OK", width="stretch") st.button("Submit", width="stretch") st.button("Download File", width="stretch") st.button( "This is a really long button label that should test wrapping", width="stretch" ) st.button("X", width="stretch") with st.container(horizontal=True, key="layout-horizontal-inputs"): st.date_input("Date Range", date(1970, 1, 1)) st.selectbox("Group by", ["Foo"]) st.multiselect("Deployment", ["All"], default=["All"]) st.multiselect( "Organization type", ["Customer", "Partner"], default=["Customer", "Partner"], ) st.multiselect("Account", ["All"], default=["All"]) with st.container(horizontal=True, border=True, key="layout-horizontal-checkboxes"): st.checkbox("", width="stretch", key="checkbox1") st.checkbox("", width="stretch", key="checkbox2") st.checkbox("", width="stretch", key="checkbox3") st.checkbox("", width="stretch", key="checkbox4") st.checkbox("", width="stretch", key="checkbox5") st.checkbox("", width="stretch", key="checkbox6") st.checkbox("", width="stretch", key="checkbox7") st.checkbox("", width="stretch", key="checkbox8") st.checkbox("", width="stretch", key="checkbox9") st.checkbox("", width="stretch", key="checkbox10") with st.container(horizontal=True, border=True, key="layout-horizontal-text-area-info"): st.info("Info") st.text_area("Notes", height=80, width="stretch") small_data = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) medium_data = pd.DataFrame( { "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "Age": [25, 30, 35, 28, 32], "City": ["New York", "London", "Tokyo", "Paris", "Sydney"], "Salary": [50000, 60000, 70000, 55000, 65000], "Department": ["Engineering", "Marketing", "Sales", "HR", "Finance"], } ) with st.container(horizontal=True, border=True, key="layout-horizontal-dataframes"): st.dataframe(small_data, width="content") st.dataframe(medium_data, width="content") st.dataframe(small_data, width="stretch") with st.container( horizontal=True, border=True, key="layout-horizontal-nested-containers" ): with st.container(horizontal=True, border=True): st.markdown("Hello, how are you? Do you like ice cream?") with st.container(horizontal=True, border=True): st.markdown("Hello. Goodbye. So long.") with st.container(horizontal=True, border=True): st.markdown("Hello") st.info("(I like ice cream)") with st.container(horizontal=True, border=True, key="layout-horizontal-columns"): col1, col2, col3 = st.columns(3) col1.markdown("Hello, how are you? Do you like ice cream?") col2.markdown("Hello. Goodbye. So long.") col3.markdown("Hello") st.info("(I like ice cream)") with st.container(horizontal=True, border=True, key="layout-horizontal-button-groups"): st.segmented_control("Segmented Control", ["Option 1", "Option 2", "Option 3"]) st.feedback("thumbs", width="stretch") st.pills("Priority", ["Low", "Medium", "High"], width="stretch") with st.container(horizontal=True, border=True, key="layout-horizontal-line-charts"): # Create sample data for line charts chart_data1 = pd.DataFrame({"x": range(10), "y": [i**2 for i in range(10)]}) chart_data2 = pd.DataFrame({"x": range(8), "y": [i * 2 + 1 for i in range(8)]}) chart_data3 = pd.DataFrame({"x": range(12), "y": [abs(i - 6) for i in range(12)]}) st.line_chart(chart_data1, x="x", y="y", width="content") st.line_chart(chart_data2, x="x", y="y", width="stretch") st.line_chart(chart_data3, x="x", y="y", width="stretch")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_min_width.py", "license": "Apache License 2.0", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_min_width_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import get_element_by_key CONTAINER_KEYS = [ "layout-horizontal-markdown", "layout-horizontal-buttons", "layout-horizontal-inputs", "layout-horizontal-checkboxes", "layout-horizontal-text-area-info", "layout-horizontal-dataframes", "layout-horizontal-nested-containers", "layout-horizontal-columns", "layout-horizontal-button-groups", "layout-horizontal-line-charts", ] @pytest.mark.parametrize("container_key", CONTAINER_KEYS) def test_container_regular_viewport( app: Page, assert_snapshot: ImageCompareFunction, container_key: str ): """Test container layouts at regular screen width.""" container_element = get_element_by_key(app, container_key) assert_snapshot( container_element, name=f"st_layouts_container_min_width-{container_key.replace('layout-horizontal-', '')}_regular", ) @pytest.mark.parametrize("container_key", CONTAINER_KEYS) def test_container_reduced_viewport( app: Page, assert_snapshot: ImageCompareFunction, container_key: str ): """Test container layouts at reduced viewport (390px).""" app.set_viewport_size({"width": 390, "height": 844}) container_element = get_element_by_key(app, container_key) assert_snapshot( container_element, name=f"st_layouts_container_min_width-{container_key.replace('layout-horizontal-', '')}_reduced", )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_min_width_test.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_layouts_container_various_elements.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import numpy as np import numpy.typing as npt import pandas as pd import streamlit as st # Common data used across multiple cases img: npt.NDArray[np.int64] = np.repeat(0, 75000).reshape(300, 250) small_data = pd.DataFrame( { "x": list(range(5)), "y": [i * i for i in range(5)], } ) CONTAINER_CASES = [ "layout-dashboard-example", "layout-horizontal-form", "layout-horizontal-expander-dataframe", "layout-horizontal-expander-dataframe-content-width", "layout-horizontal-expander-dataframe-content-width-large", "layout-horizontal-images-center", "layout-horizontal-images-distribute", "layout-horizontal-columns", "layout-horizontal-tabs", "layout-horizontal-map", "layout-horizontal-content-width", "layout-horizontal-text-area", "layout-vertical-stretch-height", "layout-vertical-content-width-container-with-various-elements", "layout-vertical-content-width-container-with-stretch-width-dataframes", "layout-vertical-content-width-container-with-content-width-dataframes", "layout-horizontal-content-width-container-with-metrics-dataframes-line-charts", "layout-vertical-content-width-container-with-map", "narrow-fixed-width-container-with-dataframe", ] selected_case = st.selectbox("Select container case", CONTAINER_CASES, index=None) if selected_case == "layout-dashboard-example": with st.container( border=False, horizontal=False, key="layout-dashboard-example", ): st.title("Q3 Results") st.subheader("Sales Performance") with st.container( border=True, horizontal=True, ): st.line_chart(small_data.set_index("x"), width=300) with st.container( border=False, horizontal=False, ): st.metric(label="Metric", value=156, delta=10, height=100, width=70) st.dataframe(small_data) elif selected_case == "layout-horizontal-form": with st.container( border=True, horizontal=True, key="layout-horizontal-form", ): with st.form("Form", width=400): st.text_input("Name") st.number_input("Age") st.selectbox("Gender", ["Male", "Female"]) st.text_area("Message") st.form_submit_button("Submit") with st.container(border=False, horizontal=False): st.info( "Please fill out the form to continue. We value your input!", width=250 ) st.image(img) elif selected_case == "layout-horizontal-expander-dataframe": with st.container( border=True, horizontal=True, key="layout-horizontal-expander-dataframe", ): with st.expander("Expand me"): st.title("Hidden Chart") st.bar_chart(small_data.set_index("x")) st.dataframe(small_data) elif selected_case == "layout-horizontal-expander-dataframe-content-width": with st.container( border=True, horizontal=True, key="layout-horizontal-expander-dataframe-content-width", ): with st.expander("Expand me"): st.title("Hidden Chart") st.bar_chart(small_data.set_index("x")) st.dataframe(small_data, width="content") elif selected_case == "layout-horizontal-expander-dataframe-content-width-large": df = pd.DataFrame( { "x": list(range(5)), "y": [i * i for i in range(5)], "z": [i * i * i for i in range(5)], "w": [i * i * i * i for i in range(5)], "v": [i * i * i * i * i for i in range(5)], "u": [i * i * i * i * i * i for i in range(5)], "t": [i * i * i * i * i * i * i for i in range(5)], "s": [i * i * i * i * i * i * i * i for i in range(5)], "r": [i * i * i * i * i * i * i * i * i for i in range(5)], "q": [i * i * i * i * i * i * i * i * i * i for i in range(5)], "p": [i * i * i * i * i * i * i * i * i * i * i for i in range(5)], "o": [i * i * i * i * i * i * i * i * i * i * i * i for i in range(5)], } ) with st.container( border=True, horizontal=True, key="layout-horizontal-expander-dataframe-content-width-large", ): with st.expander("Expand me"): st.title("Hidden Chart") st.bar_chart(df.set_index("x")) st.dataframe(df, width="content") elif selected_case == "layout-horizontal-images-center": with st.container( border=True, horizontal=True, gap=None, horizontal_alignment="center", key="layout-horizontal-images-center", ): st.image(img, width=100) st.image(img, width=100) st.image(img, width=100) elif selected_case == "layout-horizontal-images-distribute": with st.container( border=True, horizontal=True, horizontal_alignment="distribute", vertical_alignment="center", key="layout-horizontal-images-distribute", ): st.image(img, width=200) st.image(img, width=50) st.image(img) elif selected_case == "layout-horizontal-columns": with st.container(border=True, horizontal=False, key="layout-horizontal-columns"): st.title("Columns") with st.container(border=False, horizontal=True): col1, col2 = st.columns(2) with col1: with st.container( border=False, horizontal=True, ): st.info("Very important information", width=150) st.dataframe(small_data, width="content") with col2: st.dataframe(small_data, width="stretch") elif selected_case == "layout-horizontal-tabs": import altair as alt with st.container(border=True, horizontal=True, key="layout-horizontal-tabs"): st.title("Tabs", width=150) tab1, tab2 = st.tabs(["Tab 1", "Tab 2"]) with tab1: with st.container( border=False, horizontal=True, ): st.info("This is a tab") st.dataframe(small_data) with tab2: with st.container( border=False, horizontal=False, ): st.altair_chart(alt.Chart(small_data).mark_bar().encode(x="x", y="y")) st.warning("This is a warning") elif selected_case == "layout-horizontal-map": with st.container( border=True, horizontal=True, key="layout-horizontal-map", ): st.map(pd.DataFrame({"lat": [37.76, 37.77], "lon": [-122.4, -122.41]})) st.markdown( """ # Hello ## Hello ### Hello #### Hello ##### Hello ###### Hello """, width="content", ) elif selected_case == "layout-horizontal-content-width": with st.container( border=True, horizontal=True, key="layout-horizontal-content-width" ): st.markdown( """ # Hello beautiful ## Hello beautiful ### Hello beautiful #### Hello beautiful ###### Hello beautiful """, width="content", ) st.markdown( """ # Hello ## Hello ### Hello #### Hello ###### Hello """, width="content", ) elif selected_case == "layout-horizontal-text-area": with st.container(horizontal=True, height=300, key="layout-horizontal-text-area"): st.text_area("Hello", width="stretch", height="stretch") st.text_area("Hello", width="stretch") st.container(border=True, width="stretch") elif selected_case == "layout-vertical-stretch-height": with st.container(key="layout-vertical-stretch-height", border=True, height=400): df = pd.DataFrame( { "x": list(range(5)), "y": [i * i for i in range(5)], } ) st.dataframe(df, height="stretch") st.dataframe(df, height="stretch") st.markdown("Hello") elif selected_case == "layout-vertical-content-width-container-with-various-elements": with st.container( width="content", border=True, key="layout-vertical-content-width-container-with-various-elements", horizontal_alignment="center", ): st.line_chart(small_data, width="content") st.markdown("Growth in the last 3 months", width="content") elif ( selected_case == "layout-vertical-content-width-container-with-stretch-width-dataframes" ): medium_data = pd.DataFrame( { "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "Age": [25, 30, 35, 28, 32], "City": ["New York", "London", "Tokyo", "Paris", "Sydney"], "Salary": [50000, 60000, 70000, 55000, 65000], "Department": ["Engineering", "Marketing", "Sales", "HR", "Finance"], } ) with st.container( width="content", border=True, key="layout-vertical-content-width-container-with-stretch-width-dataframes", ): st.dataframe(small_data, width="stretch") st.dataframe(medium_data, width="stretch") elif ( selected_case == "layout-vertical-content-width-container-with-content-width-dataframes" ): medium_data = pd.DataFrame( { "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "Age": [25, 30, 35, 28, 32], "City": ["New York", "London", "Tokyo", "Paris", "Sydney"], "Salary": [50000, 60000, 70000, 55000, 65000], "Department": ["Engineering", "Marketing", "Sales", "HR", "Finance"], } ) with st.container( width="content", border=True, key="layout-vertical-content-width-container-with-content-width-dataframes", ): st.dataframe(small_data, width="content") st.dataframe(medium_data, width="content") elif ( selected_case == "layout-horizontal-content-width-container-with-metrics-dataframes-line-charts" ): medium_data = pd.DataFrame( { "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "Age": [25, 30, 35, 28, 32], "City": ["New York", "London", "Tokyo", "Paris", "Sydney"], "Salary": [50000, 60000, 70000, 55000, 65000], "Department": ["Engineering", "Marketing", "Sales", "HR", "Finance"], } ) chart_data1 = pd.DataFrame({"x": range(10), "y": [i**2 for i in range(10)]}) with st.container( width=700, key="layout-horizontal-content-width-container-with-metrics-dataframes-line-charts", ): with st.container( horizontal=True, width="content", border=True, gap="medium", ): st.metric("Metric", "100", width="stretch") st.dataframe(medium_data, width="stretch") st.line_chart(chart_data1, width="stretch") elif selected_case == "layout-vertical-content-width-container-with-map": with st.container( width="content", border=True, key="layout-vertical-content-width-container-with-map", ): map_data = pd.DataFrame( { "lat": [37.7749, 37.8044, 37.7599], "lon": [-122.4194, -122.2712, -122.4148], } ) st.map(map_data, width="stretch") elif selected_case == "narrow-fixed-width-container-with-dataframe": medium_data = pd.DataFrame( { "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "Age": [25, 30, 35, 28, 32], "City": ["New York", "London", "Tokyo", "Paris", "Sydney"], "Salary": [50000, 60000, 70000, 55000, 65000], "Department": ["Engineering", "Marketing", "Sales", "HR", "Finance"], } ) with st.container( width=100, border=True, key="narrow-fixed-width-container-with-dataframe" ): st.dataframe(medium_data, width="stretch")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_various_elements.py", "license": "Apache License 2.0", "lines": 346, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_layouts_container_various_elements_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import get_element_by_key, select_selectbox_option from e2e_playwright.shared.react18_utils import wait_for_react_stability # Container keys that should be tested (excluding map cases which need special handling) CONTAINER_KEYS = [ "layout-dashboard-example", "layout-horizontal-form", "layout-horizontal-expander-dataframe", "layout-horizontal-expander-dataframe-content-width", "layout-horizontal-expander-dataframe-content-width-large", "layout-horizontal-images-center", "layout-horizontal-images-distribute", "layout-horizontal-columns", "layout-horizontal-tabs", "layout-horizontal-content-width", "layout-horizontal-text-area", "layout-vertical-stretch-height", "layout-vertical-content-width-container-with-various-elements", "layout-vertical-content-width-container-with-stretch-width-dataframes", "layout-vertical-content-width-container-with-content-width-dataframes", "layout-horizontal-content-width-container-with-metrics-dataframes-line-charts", "narrow-fixed-width-container-with-dataframe", ] # Container keys that have expanders to test CONTAINER_KEYS_WITH_EXPANDERS = [ "layout-horizontal-expander-dataframe", "layout-horizontal-expander-dataframe-content-width", ] # Container keys with maps that need special handling MAP_CONTAINER_KEYS = [ "layout-horizontal-map", "layout-vertical-content-width-container-with-map", ] def test_layouts_container_various_elements( app: Page, assert_snapshot: ImageCompareFunction ): """Snapshot test for each top-level container in st_layouts_container_various_elements.py.""" for container_key in CONTAINER_KEYS: select_selectbox_option(app, "Select container case", container_key) app.wait_for_timeout(500) wait_for_react_stability(app) locator = get_element_by_key(app, container_key) expect(locator).to_be_visible() assert_snapshot( locator, name=f"st_layouts_container_various_elements-{container_key}" ) # Pydeck snapshots behavior is inconsistent for non-Chromium browsers in CI. @pytest.mark.only_browser("chromium") def test_layouts_container_with_map(app: Page, assert_snapshot: ImageCompareFunction): """Snapshot test for containers with maps in st_layouts_container_various_elements.py.""" for container_key in MAP_CONTAINER_KEYS: select_selectbox_option(app, "Select container case", container_key) # Wait for map elements to load map_element = app.get_by_test_id("stDeckGlJsonChart") expect(map_element).to_be_visible(timeout=15000) # The map assets can take more time to load, add an extra timeout # to prevent flakiness. app.wait_for_timeout(5000) locator = get_element_by_key(app, container_key) expect(locator).to_be_visible() # Use higher pixel threshold for containers with maps due to their flakiness assert_snapshot( locator, name=f"st_layouts_container_various_elements-{container_key}", pixel_threshold=0.1, ) @pytest.mark.flaky(reruns=3) def test_layouts_container_expanders(app: Page, assert_snapshot: ImageCompareFunction): """Test expander functionality in containers that contain expanders.""" for container_key in CONTAINER_KEYS_WITH_EXPANDERS: select_selectbox_option(app, "Select container case", container_key) container = get_element_by_key(app, container_key) expect(container).to_be_visible() # Get the expander in this container expander = container.get_by_test_id("stExpander") expect(expander).to_be_visible() expander.click() # Wait for the expander to open expect(expander.get_by_test_id("stExpanderDetails")).to_be_visible() # Additional timeout to avoid flakiness with rendering app.wait_for_timeout(1000) assert_snapshot( container, name=f"st_layouts_container_various_elements-{container_key}-expander-opened", )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_layouts_container_various_elements_test.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:scripts/sync_vscode_devcontainer.py
#!/usr/bin/env python # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import argparse import json import os import subprocess import sys from typing import Any, cast # Extensions to exclude from devcontainer configuration file DEVCONTAINER_EXCLUDED_EXTENSIONS = [ "anysphere.cursorpyright", ] class DevcontainerSync: """Handles synchronization between VSCode and devcontainer configurations.""" def __init__(self, repo_root: str | None = None) -> None: """Initialize with repository root path. Parameters ---------- repo_root : str | None, default None Repository root directory. If None, auto-detected from script location. """ self.repo_root = repo_root or self._get_repo_root() self.vscode_settings_path = os.path.join( self.repo_root, ".vscode", "settings.json" ) self.vscode_extensions_path = os.path.join( self.repo_root, ".vscode", "extensions.json" ) self.devcontainer_path = os.path.join( self.repo_root, ".devcontainer", "devcontainer.json" ) @staticmethod def _get_repo_root() -> str: """Get repository root directory from script location. Returns ------- str Absolute path to the repository root directory """ return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def _load_json_file(self, file_path: str) -> dict[str, Any]: """Load and parse a JSON file. Parameters ---------- file_path : str Path to the JSON file Returns ------- dict[str, Any] Parsed JSON content as dictionary Raises ------ SystemExit If file cannot be loaded or parsed """ try: with open(file_path, encoding="utf-8") as f: return cast("dict[str, Any]", json.load(f)) except FileNotFoundError: print(f"Error: File not found: {file_path}") raise SystemExit(1) except json.JSONDecodeError as e: print(f"Error: Invalid JSON in {file_path}: {e}") raise SystemExit(1) def _save_json_file(self, file_path: str, data: dict[str, Any]) -> None: """Save data to a JSON file with proper formatting. Parameters ---------- file_path : str Path to save the JSON file data : dict[str, Any] Data to save Raises ------ SystemExit If file cannot be saved """ try: with open(file_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) f.write("\n") # Add final newline print(f"Successfully updated: {file_path}") except Exception as e: print(f"Error: Failed to save {file_path}: {e}") sys.exit(1) @staticmethod def _filter_extensions(extensions: list[str]) -> list[str]: """Filter out extensions that should not be included in devcontainer. Parameters ---------- extensions : list[str] List of VSCode extensions Returns ------- list[str] Filtered list of extensions with excluded items removed """ return [ ext for ext in extensions if ext not in DEVCONTAINER_EXCLUDED_EXTENSIONS ] def _get_devcontainer_vscode_config( self, devcontainer_config: dict[str, Any] ) -> dict[str, Any]: """Get or create the VSCode configuration section in devcontainer config. Parameters ---------- devcontainer_config : dict[str, Any] The devcontainer configuration dictionary Returns ------- dict[str, Any] The VSCode configuration section """ if "customizations" not in devcontainer_config: devcontainer_config["customizations"] = {} if "vscode" not in devcontainer_config["customizations"]: devcontainer_config["customizations"]["vscode"] = {} return cast("dict[str, Any]", devcontainer_config["customizations"]["vscode"]) def _load_all_configs( self, ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: """Load all configuration files. Returns ------- tuple[dict[str, Any], dict[str, Any], dict[str, Any]] Tuple containing (VSCode settings, VSCode extensions, devcontainer config) """ vscode_settings = self._load_json_file(self.vscode_settings_path) vscode_extensions = self._load_json_file(self.vscode_extensions_path) devcontainer_config = self._load_json_file(self.devcontainer_path) return vscode_settings, vscode_extensions, devcontainer_config def _format_with_prettier(self, file_paths: list[str]) -> None: """Format JSON files using prettier. Parameters ---------- file_paths : list[str] List of file paths to format """ if not file_paths: return try: # Convert to relative paths from repo root relative_paths = [ os.path.relpath(path, self.repo_root) if os.path.isabs(path) else path for path in file_paths ] cmd = [ "./scripts/run_in_subdirectory.py", "frontend", "yarn", "exec", "prettier", "--write", "--config", "./.prettierrc", ] # Add file paths with proper relative path prefix cmd.extend(f"../{relative_path}" for relative_path in relative_paths) print("Formatting JSON files with prettier...") result = subprocess.run( cmd, check=False, cwd=self.repo_root, capture_output=True, text=True ) if result.returncode != 0: print(f"Warning: Prettier formatting failed: {result.stderr}") print(f"Command: {' '.join(cmd)}") else: print("βœ… JSON files formatted successfully") except Exception as e: print(f"Warning: Failed to format files with prettier: {e}") def check_sync_status(self) -> bool: """Check if the files are in sync without modifying them. Returns ------- bool True if files are in sync, False otherwise """ try: vscode_settings, vscode_extensions, devcontainer_config = ( self._load_all_configs() ) vscode_config = self._get_devcontainer_vscode_config(devcontainer_config) # Check extensions sync expected_extensions = self._filter_extensions( vscode_extensions.get("recommendations", []) ) actual_extensions = vscode_config.get("extensions", []) if expected_extensions != actual_extensions: print("❌ Extensions are out of sync:") print(f" VSCode extensions: {len(expected_extensions)} items") print(f" Devcontainer extensions: {len(actual_extensions)} items") return False # Check settings sync actual_settings = vscode_config.get("settings", {}) if vscode_settings != actual_settings: print("❌ Settings are out of sync:") print(f" VSCode settings: {len(vscode_settings)} items") print(f" Devcontainer settings: {len(actual_settings)} items") return False print("βœ… All files are in sync!") return True except Exception as e: print(f"❌ Error checking sync status: {e}") return False def sync_configurations(self) -> bool: """Sync VSCode settings and extensions with devcontainer configuration. Returns ------- bool True if sync was successful, False otherwise """ print("Loading source files...") vscode_settings, vscode_extensions, devcontainer_config = ( self._load_all_configs() ) # Validate extensions structure if "recommendations" not in vscode_extensions: print("Error: 'recommendations' key not found in .vscode/extensions.json") return False print("Syncing extensions and settings...") # Get filtered extensions extensions_list = self._filter_extensions(vscode_extensions["recommendations"]) # Update devcontainer configuration vscode_config = self._get_devcontainer_vscode_config(devcontainer_config) vscode_config["extensions"] = extensions_list vscode_config["settings"] = vscode_settings print("Saving updated devcontainer configuration...") self._save_json_file(self.devcontainer_path, devcontainer_config) # Format with prettier self._format_with_prettier( [ self.vscode_settings_path, self.vscode_extensions_path, self.devcontainer_path, ] ) # Print summary original_count = len(vscode_extensions["recommendations"]) excluded_count = original_count - len(extensions_list) print("βœ… Synchronization complete!") print( f" - Synced {len(extensions_list)} extensions (excluded {excluded_count} non-devcontainer extensions)" ) print(f" - Synced {len(vscode_settings)} settings") return True def _parse_arguments() -> argparse.Namespace: """Parse command line arguments. Returns ------- argparse.Namespace Parsed command line arguments containing check flag """ parser = argparse.ArgumentParser( description="Sync VSCode settings and extensions with devcontainer configuration" ) parser.add_argument( "--check", action="store_true", help="Check if files are in sync without modifying them (useful for pre-commit hooks)", ) return parser.parse_args() def main() -> None: """Main entry point for the script. Parses command line arguments and executes the appropriate sync or check operation. Exits with status 0 on success, 1 on failure. """ args = _parse_arguments() syncer = DevcontainerSync() if args.check: print("πŸ” Checking VSCode/devcontainer configuration sync...") success = syncer.check_sync_status() else: print("πŸ”„ Syncing VSCode configuration with devcontainer...") success = syncer.sync_configurations() sys.exit(0 if success else 1) if __name__ == "__main__": main()
{ "repo_id": "streamlit/streamlit", "file_path": "scripts/sync_vscode_devcontainer.py", "license": "Apache License 2.0", "lines": 289, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_sidebar_flicker.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import streamlit as st # Get the test mode from query params test_mode = st.query_params.get("test_mode", "collapsed") # Configure page based on test mode if test_mode == "collapsed": st.set_page_config( page_title="Sidebar Flicker Test - Collapsed", initial_sidebar_state="collapsed" ) elif test_mode == "expanded": st.set_page_config( page_title="Sidebar Flicker Test - Expanded", initial_sidebar_state="expanded" ) elif test_mode == "auto": st.set_page_config( page_title="Sidebar Flicker Test - Auto", initial_sidebar_state="auto" ) elif test_mode == "no_config": # Don't call set_page_config at all pass else: st.error(f"Unknown test mode: {test_mode}") # Main content st.title("Sidebar Flicker Test") st.write(f"Test mode: {test_mode}") # Add some sidebar content with st.sidebar: st.header("Sidebar Content") st.write("This is sidebar content") st.button("Sidebar Button") st.selectbox("Sidebar Select", ["Option 1", "Option 2", "Option 3"]) # Add main content st.write("This is main content") st.button("Main Button")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_sidebar_flicker.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_sidebar_flicker_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import build_app_url, wait_for_app_loaded, wait_until def setup_viewport(page: Page, viewport_type: str) -> None: """Set up viewport for testing.""" if viewport_type == "mobile": page.set_viewport_size({"width": 640, "height": 800}) else: page.set_viewport_size({"width": 1280, "height": 720}) def get_expected_sidebar_state(initial_state: str, viewport: str) -> str: """Calculate expected sidebar state based on config and viewport.""" if initial_state == "collapsed": return "collapsed" if initial_state == "expanded": return "expanded" return "collapsed" if viewport == "mobile" else "expanded" def verify_sidebar_state(page: Page, expected_state: str) -> None: """Verify sidebar exists and has expected expanded state.""" sidebar = page.get_by_test_id("stSidebar") expect(sidebar).to_be_attached() expected_expanded = "true" if expected_state == "expanded" else "false" expect(sidebar).to_have_attribute("aria-expanded", expected_expanded) def create_sidebar_monitor_script() -> str: """Create JavaScript to monitor sidebar state changes during page load.""" return """ window.__sidebarStates = []; window.__monitorStarted = Date.now(); // Override setAttribute to catch aria-expanded changes const originalSetAttribute = Element.prototype.setAttribute; Element.prototype.setAttribute = function(name, value) { if (this.dataset && this.dataset.testid === 'stSidebar' && name === 'aria-expanded') { window.__sidebarStates.push({ timestamp: Date.now() - window.__monitorStarted, ariaExpanded: value, method: 'setAttribute' }); } return originalSetAttribute.call(this, name, value); }; // Monitor DOM mutations const observer = new MutationObserver(() => { const sidebar = document.querySelector('[data-testid="stSidebar"]'); if (sidebar) { const ariaExpanded = sidebar.getAttribute('aria-expanded'); const lastState = window.__sidebarStates[window.__sidebarStates.length - 1]; if (!lastState || lastState.ariaExpanded !== ariaExpanded) { window.__sidebarStates.push({ timestamp: Date.now() - window.__monitorStarted, ariaExpanded: ariaExpanded, method: 'mutation' }); } } }); observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-expanded'] }); """ def check_for_sidebar_flicker(page: Page, initial_state: str) -> None: """Check captured sidebar states for any flickering behavior.""" states = page.evaluate("window.__sidebarStates || []") if not states: return # No state changes captured # Check for flicker in collapsed state (most common issue) if initial_state == "collapsed": for state in states: if state["ariaExpanded"] == "true": # Found flicker - sidebar was expanded when it should stay collapsed states_str = "\n".join( [ f" {s['timestamp']}ms: aria-expanded={s['ariaExpanded']} (via {s['method']})" for s in states ] ) # Use pytest.fail for custom error message pytest.fail( f"Sidebar flickered! Started expanded then collapsed.\nState changes:\n{states_str}" ) # Check for flicker in expanded state elif initial_state == "expanded": for state in states: if state["ariaExpanded"] == "false": # Found flicker - sidebar was collapsed when it should stay expanded states_str = "\n".join( [ f" {s['timestamp']}ms: aria-expanded={s['ariaExpanded']} (via {s['method']})" for s in states ] ) pytest.fail( f"Sidebar flickered! Started collapsed then expanded.\nState changes:\n{states_str}" ) def verify_no_sidebar_flicker( page: Page, initial_state: str, expected_final_state: str ) -> None: """Verify that sidebar doesn't flicker during page load. This checks both that the final state is correct AND that no intermediate flickering occurred during the loading process. """ # Wait for sidebar to be stable in expected state wait_for_sidebar_stable(page, expected_final_state) # Verify final state is correct verify_sidebar_state(page, expected_final_state) # Check for any flicker that occurred during loading check_for_sidebar_flicker(page, initial_state) def wait_for_sidebar_stable( page: Page, expected_state: str, timeout: int = 3000 ) -> None: """Wait for sidebar to reach stable state without flickering.""" sidebar = page.get_by_test_id("stSidebar") expected_expanded = "true" if expected_state == "expanded" else "false" def check_stable_state() -> bool: current_state = sidebar.get_attribute("aria-expanded") return current_state == expected_expanded wait_until(page, check_stable_state, timeout=timeout) @pytest.mark.parametrize("viewport", ["desktop", "mobile"]) @pytest.mark.parametrize("initial_sidebar_state", ["collapsed", "expanded", "auto"]) def test_sidebar_no_flicker_on_initial_load( page: Page, app_base_url: str, viewport: str, initial_sidebar_state: str ): """Test that sidebar doesn't flicker during initial page load. Verifies that when initial_sidebar_state is configured, the sidebar maintains the correct state throughout the page load process without flickering between expanded and collapsed states. """ # Set up viewport setup_viewport(page, viewport) # Determine expected final state expected_final_state = get_expected_sidebar_state(initial_sidebar_state, viewport) # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) # Navigate to the page page.goto(build_app_url(app_base_url, query={"test_mode": initial_sidebar_state})) # Wait for app to load wait_for_app_loaded(page) # Verify sidebar state without flicker verify_no_sidebar_flicker(page, initial_sidebar_state, expected_final_state) def test_sidebar_collapsed_state_no_flicker(page: Page, app_base_url: str): """Test that sidebar stays collapsed when configured as collapsed. This focused test ensures that a sidebar configured as collapsed never shows an expanded state during page load. """ setup_viewport(page, "desktop") # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) page.goto(build_app_url(app_base_url, query={"test_mode": "collapsed"})) wait_for_app_loaded(page) verify_no_sidebar_flicker(page, "collapsed", "collapsed") def test_sidebar_expanded_state_no_flicker(page: Page, app_base_url: str): """Test that sidebar stays expanded when configured as expanded. This focused test ensures that a sidebar configured as expanded maintains its expanded state during page load. """ setup_viewport(page, "desktop") # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) page.goto(build_app_url(app_base_url, query={"test_mode": "expanded"})) wait_for_app_loaded(page) verify_no_sidebar_flicker(page, "expanded", "expanded") def test_sidebar_auto_state_desktop(page: Page, app_base_url: str): """Test that sidebar auto state works correctly on desktop. On desktop, auto state should result in an expanded sidebar. """ setup_viewport(page, "desktop") # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) page.goto(build_app_url(app_base_url, query={"test_mode": "auto"})) wait_for_app_loaded(page) verify_no_sidebar_flicker(page, "auto", "expanded") def test_sidebar_auto_state_mobile(page: Page, app_base_url: str): """Test that sidebar auto state works correctly on mobile. On mobile, auto state should result in a collapsed sidebar. """ setup_viewport(page, "mobile") # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) page.goto(build_app_url(app_base_url, query={"test_mode": "auto"})) wait_for_app_loaded(page) verify_no_sidebar_flicker(page, "auto", "collapsed") def test_sidebar_no_flicker_without_page_config(page: Page, app_base_url: str): """Test sidebar behavior when set_page_config is not called. Should default to auto behavior (expanded on desktop). """ setup_viewport(page, "desktop") # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) page.goto(build_app_url(app_base_url, query={"test_mode": "no_config"})) wait_for_app_loaded(page) # Without page config, should behave like auto (expanded on desktop) verify_sidebar_state(page, "expanded") # Also check that no flicker occurred during load states = page.evaluate("window.__sidebarStates || []") if states: # Check for any unexpected state changes for state in states: if state["ariaExpanded"] == "false": states_str = "\n".join( [ f" {s['timestamp']}ms: aria-expanded={s['ariaExpanded']} (via {s['method']})" for s in states ] ) pytest.fail( f"Sidebar unexpectedly collapsed during load.\nState changes:\n{states_str}" ) def test_sidebar_stability_after_initial_load(page: Page, app_base_url: str): """Test that sidebar state remains stable after initial load. Verifies that the sidebar doesn't change state unexpectedly after the page has finished loading. """ setup_viewport(page, "desktop") # Inject monitoring script before page loads page.add_init_script(create_sidebar_monitor_script()) page.goto(build_app_url(app_base_url, query={"test_mode": "collapsed"})) wait_for_app_loaded(page) # Verify initial state verify_sidebar_state(page, "collapsed") # Clear previous state tracking and monitor for additional changes page.evaluate("window.__sidebarStates = []; window.__monitorStarted = Date.now();") # Wait a bit more and verify state hasn't changed page.wait_for_timeout(1000) verify_sidebar_state(page, "collapsed") # Check that no state changes occurred during the wait states = page.evaluate("window.__sidebarStates || []") if states: states_str = "\n".join( [ f" {s['timestamp']}ms: aria-expanded={s['ariaExpanded']} (via {s['method']})" for s in states ] ) pytest.fail( f"Sidebar state changed after initial load.\nState changes:\n{states_str}" ) # Verify sidebar is still attached and stable sidebar = page.get_by_test_id("stSidebar") expect(sidebar).to_be_attached() expect(sidebar).to_have_attribute("aria-expanded", "false")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_sidebar_flicker_test.py", "license": "Apache License 2.0", "lines": 254, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/theme_header_sizes.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from size_and_weight_test_app import run_size_and_weight_test_app # type: ignore run_size_and_weight_test_app()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/theme_header_sizes.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/theme_header_sizes_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_header_font_sizes(): """Configure custom theme.""" os.environ["STREAMLIT_THEME_HEADING_FONT_SIZES"] = json.dumps( ["3rem", "45.5px", "2.5rem"] ) # Configurable separately in sidebar os.environ["STREAMLIT_THEME_SIDEBAR_HEADING_FONT_SIZES"] = json.dumps( ["1.125rem", "1.25rem", "1.5rem", "1.625rem", "1.75rem", "2rem"] ) yield del os.environ["STREAMLIT_THEME_HEADING_FONT_SIZES"] del os.environ["STREAMLIT_THEME_SIDEBAR_HEADING_FONT_SIZES"] @pytest.mark.usefixtures("configure_custom_header_font_sizes") def test_custom_theme_header_font_sizes( app: Page, assert_snapshot: ImageCompareFunction ): # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Add some additional timeout to ensure that fonts can load without # creating flakiness: app.wait_for_timeout(10000) assert_snapshot(app, name="custom_header_font_sizes", image_threshold=0.0003)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/theme_header_sizes_test.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:scripts/snapshot_cleanup.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A script to clean up orphaned e2e snapshots. Usage: python scripts/snapshot_cleanup.py [--dry-run] [--debug] [--ci] This script will analyze the e2e test files and identify snapshot files that appear to be orphaned (no longer referenced in tests). Run from the project root directory. Options: --dry-run : Show what would be deleted without actually deleting --debug : Show detailed debug information --ci : CI mode - check for orphaned snapshots and exit with non-zero status if any are found (does not delete anything) NOTE: This script is not perfect and may identify some snapshots as orphans when they aren't actually so manually review results. """ from __future__ import annotations import argparse import os import re import subprocess import sys from collections import defaultdict # MANUAL VERIFICATION REQUIRED: # The following snapshots are not detected by this script's static analysis but # are actually in use. This disallow list should be manually updated whenever the # script incorrectly identifies a snapshot as orphaned. Not a perfect solution # but follows the 80/20 rule. # Snapshots that are not detected by static analysis but are actually in use. # This list should be manually updated when the script incorrectly flags snapshots. DISALLOWED_SNAPSHOTS = { "st_map-fullscreen_expanded[webkit].png", "st_map-fullscreen_collapsed[webkit].png", "st_pydeck_chart-fullscreen_expanded[light_theme-webkit].png", "st_pydeck_chart-fullscreen_collapsed[light_theme-webkit].png", "st_dataframe-fullscreen_expanded[chromium].png", "st_dataframe-fullscreen_collapsed[chromium].png", "st_dataframe-fullscreen_expanded[webkit].png", "st_dataframe-fullscreen_collapsed[webkit].png", "st_map-fullscreen_expanded[chromium].png", "st_map-fullscreen_collapsed[chromium].png", "st_pydeck_chart-fullscreen_expanded[dark_theme-webkit].png", "st_pydeck_chart-fullscreen_collapsed[dark_theme-webkit].png", "st_pydeck_chart-fullscreen_expanded[light_theme-chromium].png", "st_pydeck_chart-fullscreen_collapsed[light_theme-chromium].png", "st_pydeck_chart-fullscreen_expanded[dark_theme-chromium].png", "st_pydeck_chart-fullscreen_collapsed[dark_theme-chromium].png", "st_layouts_container_directions_fullscreen_elements-dataframe-fullscreen_expanded[chromium].png", "st_layouts_container_directions_fullscreen_elements-dataframe-fullscreen_collapsed[chromium].png", "st_layouts_container_directions_fullscreen_elements-dataframe-fullscreen_expanded[webkit].png", "st_layouts_container_directions_fullscreen_elements-dataframe-fullscreen_collapsed[webkit].png", "st_layouts_container_directions_fullscreen_elements-dataframe-fullscreen_expanded[firefox].png", "st_layouts_container_directions_fullscreen_elements-dataframe-fullscreen_collapsed[firefox].png", # st_data_editor Firefox snapshots that are not detected by static analysis "st_data_editor-input_data_0[firefox].png", "st_data_editor-input_data_1[firefox].png", "st_data_editor-input_data_2[firefox].png", "st_data_editor-input_data_3[firefox].png", "st_data_editor-input_data_4[firefox].png", "st_data_editor-input_data_5[firefox].png", "st_data_editor-input_data_6[firefox].png", "st_data_editor-input_data_7[firefox].png", "st_data_editor-input_data_8[firefox].png", "st_data_editor-input_data_9[firefox].png", "st_data_editor-input_data_10[firefox].png", "st_data_editor-input_data_11[firefox].png", "st_data_editor-input_data_12[firefox].png", "st_data_editor-input_data_13[firefox].png", "st_data_editor-input_data_14[firefox].png", "st_data_editor-input_data_15[firefox].png", "st_data_editor-input_data_16[firefox].png", "st_data_editor-input_data_17[firefox].png", "st_data_editor-input_data_18[firefox].png", "st_data_editor-input_data_19[firefox].png", "st_data_editor-input_data_20[firefox].png", "st_data_editor-input_data_21[firefox].png", "st_data_editor-input_data_22[firefox].png", "st_data_editor-input_data_23[firefox].png", "st_data_editor-input_data_24[firefox].png", "st_data_editor-input_data_25[firefox].png", "st_data_editor-input_data_26[firefox].png", "st_data_editor-input_data_27[firefox].png", "st_data_editor-input_data_28[firefox].png", "st_data_editor-input_data_29[firefox].png", "st_data_editor-input_data_30[firefox].png", "st_data_editor-input_data_31[firefox].png", "st_data_editor-input_data_32[firefox].png", "st_data_editor-input_data_33[firefox].png", "st_data_editor-input_data_34[firefox].png", # st_chat_input file chip snapshots that are not detected by static analysis "st_chat_input-file_chip_archive[chromium-archive].png", "st_chat_input-file_chip_archive[firefox-archive].png", "st_chat_input-file_chip_archive[webkit-archive].png", "st_chat_input-file_chip_audio[chromium-audio].png", "st_chat_input-file_chip_audio[firefox-audio].png", "st_chat_input-file_chip_audio[webkit-audio].png", "st_chat_input-file_chip_code[chromium-code].png", "st_chat_input-file_chip_code[firefox-code].png", "st_chat_input-file_chip_code[webkit-code].png", "st_chat_input-file_chip_pdf[chromium-pdf].png", "st_chat_input-file_chip_pdf[firefox-pdf].png", "st_chat_input-file_chip_pdf[webkit-pdf].png", "st_chat_input-file_chip_spreadsheet[chromium-spreadsheet].png", "st_chat_input-file_chip_spreadsheet[firefox-spreadsheet].png", "st_chat_input-file_chip_spreadsheet[webkit-spreadsheet].png", "st_chat_input-file_chip_text[chromium-text].png", "st_chat_input-file_chip_text[firefox-text].png", "st_chat_input-file_chip_text[webkit-text].png", "st_chat_input-file_chip_truncated[chromium-truncated].png", "st_chat_input-file_chip_truncated[firefox-truncated].png", "st_chat_input-file_chip_truncated[webkit-truncated].png", "st_chat_input-file_chip_unknown[chromium-unknown].png", "st_chat_input-file_chip_unknown[firefox-unknown].png", "st_chat_input-file_chip_unknown[webkit-unknown].png", "st_chat_input-file_chip_video[chromium-video].png", "st_chat_input-file_chip_video[firefox-video].png", "st_chat_input-file_chip_video[webkit-video].png", } def get_used_snapshots() -> dict[str, tuple[set[str], set[str]]]: """ Scans all test files to find snapshot names used in `assert_snapshot` calls. Returns ------- A dictionary where keys are test names (e.g., "st_button_test") and values are tuples of (exact_names, prefixes) where: - exact_names: Set of exact snapshot names (from regular strings) - prefixes: Set of snapshot name prefixes (from f-strings) """ snapshots_by_test: dict[str, tuple[set[str], set[str]]] = defaultdict( lambda: (set(), set()) ) try: cmd = "find e2e_playwright -name '*_test.py'" result = subprocess.run( cmd, shell=True, capture_output=True, text=True, check=True ) test_files = result.stdout.strip().split("\n") except subprocess.CalledProcessError as e: print(f"Error finding test files: {e}") return snapshots_by_test for test_file in test_files: try: with open(test_file, encoding="utf-8") as f: content = f.read() test_name = os.path.basename(test_file).replace(".py", "") exact_names, prefixes = snapshots_by_test[test_name] # Find all assert_snapshot calls, including multi-line ones lines = content.split("\n") for i, line in enumerate(lines): if "assert_snapshot" in line: # Look at this line and the next few lines to capture multi-line calls context = "\n".join(lines[i : min(i + 10, len(lines))]) # First check for string concatenation patterns like "prefix" + str(i) concat_match = re.search( r'name\s*=\s*["\']([^"\']+)["\']\s*\+', context ) if concat_match: prefix = concat_match.group(1) prefixes.add(prefix) continue # Then check for f-strings or regular strings name_match = re.search( r'name\s*=\s*(f?)["\']([^"\']+)["\']', context ) if name_match: is_fstring = name_match.group(1) == "f" snapshot_name = name_match.group(2) if is_fstring: # For f-strings, extract the prefix before the first { prefix_end = snapshot_name.find("{") if prefix_end > 0: prefix = snapshot_name[:prefix_end] prefixes.add(prefix) else: # If no { found in f-string, treat as exact name exact_names.add(snapshot_name) else: # For regular strings, it's an exact name exact_names.add(snapshot_name) # If no name parameter found, skip this assert_snapshot call except Exception as e: print(f"Error processing {test_file}: {e}") return dict(snapshots_by_test) def search_for_snapshot_name(snapshot_name: str) -> bool: """ Search for a snapshot name in all e2e test files. Returns True if found, False otherwise. """ try: # Use grep to search for the snapshot name in all test files cmd = f'grep -r --include="*.py" "{snapshot_name}" e2e_playwright/' result = subprocess.run( cmd, shell=True, capture_output=True, text=True, check=False ) # If grep finds something, it returns 0 return result.returncode == 0 except Exception as e: print(f"Error searching for {snapshot_name}: {e}") # If there's an error, be conservative and assume it's used return True def main() -> None: """Finds and deletes all orphaned snapshot files.""" parser = argparse.ArgumentParser( prog="snapshot_cleanup.py", description="Clean up orphaned e2e snapshots" ) parser.add_argument( "--dry-run", action="store_true", help="Show what would be deleted without actually deleting", ) parser.add_argument( "--debug", action="store_true", help="Show detailed debug information" ) parser.add_argument( "--ci", action="store_true", help="CI mode - check for orphaned snapshots and exit with non-zero status if any are found " "(does not delete anything)", ) args = parser.parse_args() debug = args.debug dry_run = args.dry_run or debug ci = args.ci if not ci: print("Analyzing test files for snapshot usage...") snapshots_by_test = get_used_snapshots() if debug: print("\nDEBUG: Found snapshots in tests:") for test_name, (exact_names, prefixes) in sorted(snapshots_by_test.items()): if exact_names or prefixes: print(f"\n{test_name}:") if exact_names: print( f" Exact names ({len(exact_names)}): {sorted(exact_names)[:5]}" ) if len(exact_names) > 5: print(f" ... and {len(exact_names) - 5} more") if prefixes: print(f" Prefixes: {sorted(prefixes)}") orphaned_files = [] searched_snapshots = 0 snapshot_root = "e2e_playwright/__snapshots__/linux" if not ci: print(f"\nScanning {snapshot_root} for snapshot files...") all_snapshot_files = [] for dirpath, _, filenames in os.walk(snapshot_root): for filename in filenames: if filename.endswith(".png"): all_snapshot_files.append(os.path.join(dirpath, filename)) if not ci: print(f"Found {len(all_snapshot_files)} total snapshot files") debug_test: str | None = None # Debug specific test if debug and "--test" in sys.argv: test_idx = sys.argv.index("--test") if test_idx + 1 < len(sys.argv): debug_test = sys.argv[test_idx + 1] print(f"\nDEBUG: Focusing on test: {debug_test}") if not ci: print("\nChecking snapshots...") for i, filepath in enumerate(all_snapshot_files): test_name = os.path.basename(os.path.dirname(filepath)) filename = os.path.basename(filepath) # from "st_button-primary[chromium].png" -> get "st_button-primary" snapshot_name = re.sub(r"\[.*\]\.png$", "", filename) # Check if this snapshot is used is_used = False reason = "Test not found in snapshots_by_test" if test_name in snapshots_by_test: exact_names, prefixes = snapshots_by_test[test_name] # First check for exact match if snapshot_name in exact_names: is_used = True reason = "Exact match in assert_snapshot" else: # Then check if it matches any prefix for prefix in prefixes: if snapshot_name.startswith(prefix): is_used = True reason = f"Matches prefix in assert_snapshot: '{prefix}'" break # If not found in assert_snapshot calls, search for it in the codebase if not is_used: if search_for_snapshot_name(snapshot_name): is_used = True reason = "Found in codebase search" searched_snapshots += 1 else: reason = "Not found in assert_snapshot or codebase" # Check if this snapshot is in the disallow list if not is_used and filename in DISALLOWED_SNAPSHOTS: is_used = True reason = "Protected by disallow list (manually verified as in-use)" if debug and "--test" in sys.argv and test_name == debug_test: print(f"\n{filename}: {'USED' if is_used else 'ORPHANED'} - {reason}") if not is_used: orphaned_files.append(filepath) # Show progress for non-debug and non-CI runs if not debug and not ci and (i + 1) % 100 == 0: print(f" Checked {i + 1}/{len(all_snapshot_files)} files...") if not orphaned_files: if ci: print("\nβœ… CI MODE: No orphaned snapshots found.") sys.exit(0) else: print("\nNo orphaned snapshots found.") return if not ci: print(f"\nFound {len(orphaned_files)} orphaned snapshots") print( f"(Had to search codebase for {searched_snapshots} snapshots not found in assert_snapshot calls)" ) # Print a summary of what we're about to delete if not ci: print("\nSummary by test:") orphaned_by_test = defaultdict(list) for filepath in orphaned_files: test_name = os.path.basename(os.path.dirname(filepath)) orphaned_by_test[test_name].append(os.path.basename(filepath)) # Show tests with most orphans first if not ci: for test_name in sorted( orphaned_by_test.keys(), key=lambda x: len(orphaned_by_test[x]), reverse=True, ): count = len(orphaned_by_test[test_name]) print(f"\n{test_name}: {count} orphaned files") if debug or count <= 5: for filename in sorted(orphaned_by_test[test_name])[:10]: print(f" - {filename}") if count > 10: print(f" ... and {count - 10} more") else: for filename in sorted(orphaned_by_test[test_name])[:3]: print(f" - {filename}") print(f" ... and {count - 3} more") if dry_run: print(f"\nDRY RUN: Would delete {len(orphaned_files)} orphaned snapshots.") print("Run without --dry-run or --debug to actually delete them.") elif ci: print(f"\n❌ CI MODE: Found {len(orphaned_files)} orphaned snapshots!") print("\nOrphaned snapshots by test:") for test_name in sorted( orphaned_by_test.keys(), key=lambda x: len(orphaned_by_test[x]), reverse=True, ): count = len(orphaned_by_test[test_name]) print(f" {test_name}: {count} orphaned files") print("\n--- COPY_PASTE_START ---") for filename in sorted([os.path.basename(f) for f in orphaned_files]): print(f' "{filename}",') print("--- COPY_PASTE_END ---") print("\nTo fix this, run: python scripts/snapshot_cleanup.py") print("Or review the snapshots manually to ensure they're actually orphaned.") sys.exit(1) else: print(f"\nReady to delete {len(orphaned_files)} orphaned snapshots.") print("Proceeding with deletion...") for filepath in orphaned_files: try: os.remove(filepath) except FileNotFoundError: print(f"Warning: File not found and could not be deleted: {filepath}") except PermissionError: print(f"Warning: Permission denied when trying to delete: {filepath}") except Exception as e: print( f"Warning: An unexpected error occurred while deleting {filepath}: {e}" ) print(f"\nβœ… Successfully deleted {len(orphaned_files)} orphaned snapshots.") if __name__ == "__main__": main()
{ "repo_id": "streamlit/streamlit", "file_path": "scripts/snapshot_cleanup.py", "license": "Apache License 2.0", "lines": 385, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:lib/tests/streamlit/typing/cache_types.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING from typing_extensions import assert_type if TYPE_CHECKING: import streamlit as st @st.cache_data def cached_data_fn(arg1: int, arg2: str) -> bool: return True @st.cache_data(ttl=1) def cached_data_fn_with_decorator_args(arg1: int, arg2: str) -> bool: return True assert_type(cached_data_fn(1, "2"), bool) assert_type(cached_data_fn.clear(), None) assert_type(cached_data_fn.clear(1), None) assert_type(cached_data_fn.clear(1, "2"), None) assert_type(cached_data_fn.clear(1, arg2="2"), None) assert_type(cached_data_fn.clear(arg1=1), None) assert_type(cached_data_fn.clear(arg2="2"), None) assert_type(cached_data_fn.clear(arg1=1, arg2="2"), None) assert_type(cached_data_fn_with_decorator_args(1, "2"), bool) assert_type(cached_data_fn_with_decorator_args.clear(), None) assert_type(cached_data_fn_with_decorator_args.clear(1), None) assert_type(cached_data_fn_with_decorator_args.clear(1, "2"), None) assert_type(cached_data_fn_with_decorator_args.clear(1, arg2="2"), None) assert_type(cached_data_fn_with_decorator_args.clear(arg1=1), None) assert_type(cached_data_fn_with_decorator_args.clear(arg2="2"), None) assert_type(cached_data_fn_with_decorator_args.clear(arg1=1, arg2="2"), None) @st.cache_resource def cached_resource_fn(arg1: int, arg2: str) -> bool: return True @st.cache_resource(ttl=1) def cached_resource_fn_with_decorator_args(arg1: int, arg2: str) -> bool: return True assert_type(cached_resource_fn(1, "2"), bool) assert_type(cached_resource_fn.clear(), None) assert_type(cached_resource_fn.clear(1), None) assert_type(cached_resource_fn.clear(1, "2"), None) assert_type(cached_resource_fn.clear(1, arg2="2"), None) assert_type(cached_resource_fn.clear(arg1=1), None) assert_type(cached_resource_fn.clear(arg2="2"), None) assert_type(cached_resource_fn.clear(arg1=1, arg2="2"), None) assert_type(cached_resource_fn_with_decorator_args(1, "2"), bool) assert_type(cached_resource_fn_with_decorator_args.clear(), None) assert_type(cached_resource_fn_with_decorator_args.clear(1), None) assert_type(cached_resource_fn_with_decorator_args.clear(1, "2"), None) assert_type(cached_resource_fn_with_decorator_args.clear(1, arg2="2"), None) assert_type(cached_resource_fn_with_decorator_args.clear(arg1=1), None) assert_type(cached_resource_fn_with_decorator_args.clear(arg2="2"), None) assert_type(cached_resource_fn_with_decorator_args.clear(arg1=1, arg2="2"), None)
{ "repo_id": "streamlit/streamlit", "file_path": "lib/tests/streamlit/typing/cache_types.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/st_main_layout.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import streamlit as st # Get the test mode from environment variable to test different sidebar states test_mode = os.environ.get("STREAMLIT_SIDEBAR_TEST_MODE", "auto") if test_mode == "collapsed": st.set_page_config( page_title="Sidebar Test - Collapsed", initial_sidebar_state="collapsed" ) elif test_mode == "expanded": st.set_page_config( page_title="Sidebar Test - Expanded", initial_sidebar_state="expanded" ) elif test_mode == "auto": st.set_page_config(page_title="Sidebar Test - Auto", initial_sidebar_state="auto") else: # Default case - no page config set, should use default "auto" behavior st.set_page_config(page_title="Sidebar Test - Default") # Add substantial sidebar content to ensure it's detected st.sidebar.markdown("# Sidebar Content") for i in range(10): st.sidebar.text(f"This is a text {i}") # Main content st.title(f"Main Layout Test - Mode: {test_mode}") st.write(f"Testing sidebar behavior with initial_sidebar_state='{test_mode}'") # Add some main content for i in range(10): st.write(f"Main content line {i + 1}") if i % 3 == 0: st.info(f"Info box {i // 3 + 1}") st.write("End of test content")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_main_layout.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/st_main_layout_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Any import pytest from playwright.sync_api import Page, expect from e2e_playwright.conftest import ( ImageCompareFunction, build_app_url, start_app_server, wait_for_app_loaded, wait_for_app_run, ) if TYPE_CHECKING: from collections.abc import Generator @pytest.fixture def sidebar_mode(request: pytest.FixtureRequest) -> str: """Fixture to provide sidebar_mode parameter to app fixture.""" return getattr(request, "param", "auto") # Disable the module-scoped app_server fixture for this test module @pytest.fixture(scope="module", autouse=True) def app_server(): """Override to disable the default module-scoped app_server fixture.""" return # Custom app fixture that starts a fresh server for each test with the correct sidebar mode @pytest.fixture def app( page: Page, app_base_url: str, app_port: int, request: pytest.FixtureRequest, sidebar_mode: str, ) -> Generator[Page, None, None]: """Start fresh server with correct sidebar mode for each test.""" from e2e_playwright.shared.performance import start_capture_traces # Start the Streamlit server with the custom environment variable streamlit_proc = start_app_server( app_port, request.module, extra_env={"STREAMLIT_SIDEBAR_TEST_MODE": sidebar_mode}, ) try: # Open the app page response = page.goto(build_app_url(app_base_url, path="/")) if response is None or response.status != 200: raise RuntimeError("Unable to load page") # Clear localStorage to ensure clean state for tests page.evaluate("() => window.localStorage.clear()") start_capture_traces(page) wait_for_app_loaded(page) yield page finally: # Clean up the server streamlit_stdout = streamlit_proc.terminate() print(streamlit_stdout, flush=True) def setup_viewport_and_verify_title( app: Page, width: int, height: int, sidebar_mode: str ) -> None: """Common setup for viewport, waiting, and title verification.""" app.set_viewport_size({"width": width, "height": height}) # Verify the fixture was applied correctly by checking the page title expected_title = f"Sidebar Test - {sidebar_mode.title()}" expect(app).to_have_title(expected_title) # Reload the page to allow viewport size change to take effect. app.reload() wait_for_app_run(app) def verify_sidebar_state(app: Page, expected_expanded: bool) -> None: """Verify sidebar exists and has expected expanded state.""" sidebar = app.get_by_test_id("stSidebar") expect(sidebar).to_be_attached() expect(sidebar).to_have_attribute("aria-expanded", str(expected_expanded).lower()) def verify_sidebar_content_visibility(app: Page, should_be_visible: bool) -> None: """Verify sidebar content visibility.""" sidebar_content = app.get_by_test_id("stSidebarContent") if should_be_visible: expect(sidebar_content).to_be_visible() else: # For collapsed state, we don't check visibility as it might vary pass def verify_expand_button_visible(app: Page) -> None: """Verify expand button is visible.""" expand_button = app.get_by_test_id("stExpandSidebarButton") expect(expand_button).to_be_visible() # Consolidated test for basic sidebar states across different modes and viewports @pytest.mark.parametrize( ("sidebar_mode", "viewport", "expected_expanded", "test_name"), [ ("auto", {"width": 375, "height": 667}, False, "auto_mobile_collapsed"), ("auto", {"width": 1280, "height": 800}, True, "auto_desktop_expanded"), ("collapsed", {"width": 375, "height": 667}, False, "collapsed_mobile"), ("collapsed", {"width": 1280, "height": 800}, False, "collapsed_desktop"), ("expanded", {"width": 375, "height": 667}, True, "expanded_mobile"), ("expanded", {"width": 1280, "height": 800}, True, "expanded_desktop"), ], indirect=["sidebar_mode"], ) def test_sidebar_basic_states( app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str, viewport: dict[str, int], expected_expanded: bool, test_name: str, ): """Test sidebar basic states across different modes and viewport sizes.""" setup_viewport_and_verify_title( app, viewport["width"], viewport["height"], sidebar_mode ) # Verify sidebar state verify_sidebar_state(app, expected_expanded) # Verify content visibility for expanded states if expected_expanded: verify_sidebar_content_visibility(app, True) # Note: For collapsed states, we don't always verify expand button visibility # as behavior may vary between auto/collapsed modes # Take snapshot assert_snapshot(app, name=f"st_main_layout-{test_name}") # Test interaction functionality for auto mode @pytest.mark.parametrize("sidebar_mode", ["auto"], indirect=True) def test_sidebar_auto_mobile_expand_interaction( app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str ): """Test sidebar expand interaction on mobile with auto mode.""" setup_viewport_and_verify_title(app, 375, 667, sidebar_mode) # Verify initial collapsed state verify_sidebar_state(app, False) verify_expand_button_visible(app) # Expand the sidebar expand_button = app.get_by_test_id("stExpandSidebarButton") expand_button.click() # Verify expanded state verify_sidebar_state(app, True) verify_sidebar_content_visibility(app, True) # Take snapshot of expanded state assert_snapshot(app, name="st_main_layout-auto_mobile_expanded") @pytest.mark.parametrize("sidebar_mode", ["auto"], indirect=True) def test_sidebar_auto_desktop_collapse_interaction( app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str ): """Test sidebar collapse interaction on desktop with auto mode.""" setup_viewport_and_verify_title(app, 1280, 800, sidebar_mode) # Verify initial expanded state verify_sidebar_state(app, True) verify_sidebar_content_visibility(app, True) # Hover over sidebar to make collapse button visible sidebar_header = app.get_by_test_id("stSidebarHeader") sidebar_header.hover() # Collapse the sidebar collapse_button = app.get_by_test_id("stSidebarCollapseButton").locator("button") collapse_button.click() # Verify collapsed state verify_sidebar_state(app, False) verify_expand_button_visible(app) # Take snapshot of collapsed desktop state assert_snapshot(app, name="st_main_layout-auto_desktop_collapsed") # Tests for deploy button positioning @pytest.mark.parametrize( ("sidebar_mode", "viewport", "expected_expanded", "test_name"), [ ( "auto", {"width": 375, "height": 667}, False, "deploy_button_mobile_collapsed", ), ( "auto", {"width": 1280, "height": 800}, True, "deploy_button_desktop_expanded", ), ], indirect=["sidebar_mode"], ) def test_deploy_button_positioning( app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str, viewport: dict[str, int], expected_expanded: bool, test_name: str, ): """Test deploy button positioning with different sidebar states.""" setup_viewport_and_verify_title( app, viewport["width"], viewport["height"], sidebar_mode ) # Verify sidebar state verify_sidebar_state(app, expected_expanded) # Verify header is visible header = app.get_by_test_id("stHeader") expect(header).to_be_visible() # Take screenshot focusing on header area assert_snapshot(header, name=f"st_main_layout-{test_name}") @pytest.mark.parametrize("sidebar_mode", ["auto"], indirect=True) def test_deploy_button_desktop_manually_collapsed( app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str ): """Test deploy button positioning on desktop after manually collapsing sidebar.""" setup_viewport_and_verify_title(app, 1280, 800, sidebar_mode) # Manually collapse the sidebar sidebar_header = app.get_by_test_id("stSidebarHeader") sidebar_header.hover() collapse_button = app.get_by_test_id("stSidebarCollapseButton").locator("button") collapse_button.click() # Verify sidebar is collapsed verify_sidebar_state(app, False) # Verify header adjusts correctly header = app.get_by_test_id("stHeader") expect(header).to_be_visible() # Take screenshot focusing on header area assert_snapshot( header, name="st_main_layout-deploy_button_desktop_manually_collapsed" ) # Test responsive behavior during viewport size changes @pytest.mark.parametrize("sidebar_mode", ["auto"], indirect=True) def test_viewport_resize_responsive_behavior( app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str ): """Test sidebar behavior when resizing viewport with auto mode.""" # Start with desktop - sidebar should be expanded setup_viewport_and_verify_title(app, 1280, 800, sidebar_mode) verify_sidebar_state(app, True) # Resize to mobile - sidebar should auto-collapse app.set_viewport_size({"width": 375, "height": 667}) # Verify sidebar collapsed on mobile verify_sidebar_state(app, False) verify_expand_button_visible(app) # Take final snapshot assert_snapshot(app, name="st_main_layout-responsive_mobile_final") # Comprehensive responsiveness test @pytest.mark.parametrize( ("sidebar_mode", "viewport_config"), [ ("auto", {"name": "mobile", "width": 375, "height": 667}), ("auto", {"name": "tablet", "width": 768, "height": 1024}), ("auto", {"name": "desktop", "width": 1280, "height": 800}), ("auto", {"name": "wide", "width": 1920, "height": 1080}), ], indirect=["sidebar_mode"], ) def test_layout_responsiveness_auto_mode( app: Page, viewport_config: dict[str, Any], assert_snapshot: ImageCompareFunction, sidebar_mode: str, ): """Test layout responsiveness with auto sidebar mode across different viewport sizes.""" setup_viewport_and_verify_title( app, viewport_config["width"], viewport_config["height"], sidebar_mode ) # Verify basic layout elements are present header = app.get_by_test_id("stHeader") expect(header).to_be_visible() main_content = app.get_by_test_id("stMain") expect(main_content).to_be_visible() sidebar = app.get_by_test_id("stSidebar") expect(sidebar).to_be_attached() expect(app.get_by_text("Info box 1")).to_be_visible() expect(app.get_by_text("Info box 2")).to_be_visible() # Take full app screenshot for this viewport assert_snapshot( app, name=f"st_main_layout-auto_{viewport_config['name']}_responsive" )
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/st_main_layout_test.py", "license": "Apache License 2.0", "lines": 274, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/theme_font_weights_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_custom_theme_font_weights(): """Configure custom theme.""" os.environ["STREAMLIT_THEME_BASE_FONT_WEIGHT"] = "200" os.environ["STREAMLIT_THEME_CODE_FONT_WEIGHT"] = "600" os.environ["STREAMLIT_THEME_HEADING_FONT_WEIGHTS"] = json.dumps( [800, 700, 500, 400, 300, 200] ) # Configurable separately in sidebar os.environ["STREAMLIT_THEME_SIDEBAR_CODE_FONT_WEIGHT"] = "200" os.environ["STREAMLIT_THEME_SIDEBAR_HEADING_FONT_WEIGHTS"] = json.dumps( [200, 300, 400, 500, 700, 800] ) yield del os.environ["STREAMLIT_THEME_BASE_FONT_WEIGHT"] del os.environ["STREAMLIT_THEME_CODE_FONT_WEIGHT"] del os.environ["STREAMLIT_THEME_HEADING_FONT_WEIGHTS"] del os.environ["STREAMLIT_THEME_SIDEBAR_CODE_FONT_WEIGHT"] del os.environ["STREAMLIT_THEME_SIDEBAR_HEADING_FONT_WEIGHTS"] @pytest.mark.usefixtures("configure_custom_theme_font_weights") def test_custom_theme_font_weights(app: Page, assert_snapshot: ImageCompareFunction): # Set bigger viewport to better show the charts app.set_viewport_size({"width": 1280, "height": 1000}) # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Add some additional timeout to ensure that fonts can load without # creating flakiness: app.wait_for_timeout(10000) assert_snapshot(app, name="custom_weights_app", image_threshold=0.0003)
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/theme_font_weights_test.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/multipage_apps_v2/mpa_v2_top_nav.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path from typing import Any, Literal from PIL import Image import streamlit as st # Define image paths for logo testing PARENT_DIR = Path(__file__).parent.parent / "multipage_apps" LOGO_FULL = Image.open(str(PARENT_DIR / "full-streamlit.png")) LOGO_SMALL = Image.open(str(PARENT_DIR / "small-streamlit.png")) # Define page functions inline def page1(): st.header("Page 1") st.write("Page 1 Content") def page2(): st.header("Page 2") st.write("Page 2 Content") def page3(): st.header("Page 3") st.write("Page 3 Content") def page4(): st.header("Page 4") st.write("Page 4 Content") def page5(): st.header("Page 5") st.write("Page 5 Content") # Configuration checkboxes test_overflow = st.checkbox("Test Overflow (5 pages)", key="test_overflow") test_sections = st.checkbox("Test Sections", key="test_sections") test_single_section = st.checkbox( "Test Single Section (3 pages)", key="test_single_section" ) test_mixed_sections = st.checkbox( "Test Mixed Empty/Named Sections", key="test_mixed_sections" ) test_markdown_sections = st.checkbox( "Test Markdown Section Headers", key="test_markdown_sections" ) test_hidden = st.checkbox("Test Hidden Navigation", key="test_hidden") test_switching = st.checkbox("Test Navigation Switching", key="test_switching") test_sidebar = st.checkbox("Test Sidebar Content", key="test_sidebar") test_logo = st.checkbox("Test Logo", key="test_logo") # Initialize navigation position in session state if "nav_position" not in st.session_state: st.session_state.nav_position = "sidebar" if not test_hidden else "hidden" # Show navigation switching controls if test_switching: col1, col2, col3 = st.columns(3) with col1: if st.button("Switch to Top Nav"): st.session_state.nav_position = "top" st.rerun() with col2: if st.button("Switch to Sidebar"): st.session_state.nav_position = "sidebar" st.rerun() with col3: if st.button("Switch to Hidden"): st.session_state.nav_position = "hidden" st.rerun() # Define pages based on test configuration pages: Any # Will be either a list or dict of pages if test_overflow: # Create 5 pages for overflow testing pages = [ st.Page(page1, title="Page 1", icon="πŸ“„"), st.Page(page2, title="Page 2", icon="πŸ“„"), st.Page(page3, title="Page 3", icon="πŸ“„"), st.Page(page4, title="Page 4", icon="πŸ“„"), st.Page(page5, title="Page 5", icon="πŸ“„"), ] elif test_sections: # Create pages with sections pages = { "Section A": [ st.Page(page1, title="Page 1"), st.Page(page2, title="Page 2"), ], "Section B": [ st.Page(page3, title="Page 3"), st.Page(page4, title="Page 4"), ], } elif test_single_section: # Create a single section with 3 pages pages = { "My Section": [ st.Page(page1, title="Page 1", icon="🏠"), st.Page(page2, title="Page 2", icon="πŸ“Š"), st.Page(page3, title="Page 3", icon="πŸ”§"), ], } elif test_mixed_sections: # Test mixed empty and named sections (issue #12243) pages = { "": [ st.Page(page1, title="Home", icon="🏠"), st.Page(page2, title="Dashboard", icon="πŸ“Š"), ], "Admin": [ st.Page(page3, title="Settings", icon="βš™οΈ"), st.Page(page4, title="Users", icon="πŸ‘₯"), ], "Reports": [ st.Page(page5, title="Analytics", icon="πŸ“ˆ"), ], } elif test_markdown_sections: # Test markdown formatting in section headers pages = { "**Bold** Section": [ st.Page(page1, title="Page 1"), st.Page(page2, title="Page 2"), ], "*Italic* Section": [ st.Page(page3, title="Page 3"), st.Page(page4, title="Page 4"), ], ":material/settings: Icon Section": [ st.Page(page5, title="Page 5"), ], } else: # Default 3 pages pages = [ st.Page(page1, title="Page 1", icon="🏠"), st.Page(page2, title="Page 2", icon="πŸ“Š"), st.Page(page3, title="Page 3", icon="πŸ”§"), ] position: Literal["sidebar", "hidden", "top"] = "top" # Determine position if test_hidden: position = "hidden" elif test_switching: position = st.session_state.nav_position else: position = "top" # Add logo if enabled if test_logo: st.logo(LOGO_FULL, link="https://www.streamlit.io", icon_image=LOGO_SMALL) # Add sidebar content if enabled if test_sidebar: with st.sidebar: st.header("Sidebar Content") st.write("This is some static sidebar content for testing.") st.write( "Use this to test how the top navigation behaves when the sidebar is present." ) st.subheader("Sample Controls") st.slider("Sample Slider", 0, 100, 50) st.selectbox("Sample Selectbox", ["Option 1", "Option 2", "Option 3"]) st.text_input("Sample Text Input", "Default text") st.subheader("Sample Info") st.info("This sidebar helps test top nav behavior") st.success("Sidebar is working correctly!") # Add some spacing st.write("---") st.write( "Toggle this checkbox to test sidebar expand/collapse behavior with the top navigation." ) # Create navigation pg = st.navigation(pages, position=position) pg.run()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/multipage_apps_v2/mpa_v2_top_nav.py", "license": "Apache License 2.0", "lines": 174, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/multipage_apps_v2/mpa_v2_top_nav_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page, expect from e2e_playwright.conftest import ImageCompareFunction, wait_for_app_run from e2e_playwright.shared.app_utils import click_checkbox, goto_app def test_desktop_top_nav(app: Page): """Test top navigation on desktop viewport.""" # Set desktop viewport app.set_viewport_size({"width": 1280, "height": 800}) # Default configuration shows top nav with 3 pages wait_for_app_run(app) # The top nav is rendered using rc-overflow component # Check that navigation links exist and are visible nav_links = app.get_by_test_id("stTopNavLink") expect(nav_links).to_have_count(3) # 3 pages # Verify no sidebar is visible sidebar = app.get_by_test_id("stSidebar") expect(sidebar).not_to_be_visible() # Click second page nav_links.nth(1).click() wait_for_app_run(app) # Verify page content changed - be specific about which element expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() # Verify active state - check if the link has the active class or is selected # The active nav link should have some visual indication second_link = nav_links.nth(1) # Try different ways to check active state expect(second_link).to_be_visible() # Just verify it's visible for now def test_mobile_fallback_to_sidebar(app: Page): """Test that top nav falls back to sidebar on mobile.""" # Set mobile viewport app.set_viewport_size({"width": 375, "height": 667}) wait_for_app_run(app) # On mobile with AUTO state, sidebar should be collapsed by default sidebar = app.get_by_test_id("stSidebar") expect(sidebar).to_have_attribute("aria-expanded", "false") # Expand the sidebar to access navigation expand_button = app.get_by_test_id("stExpandSidebarButton") expand_button.click() # Wait for sidebar to expand and nav links to be visible expect(sidebar).to_have_attribute("aria-expanded", "true") nav_links = app.get_by_test_id("stSidebarNavLink") expect(nav_links.first).to_be_visible() # Test navigation functionality nav_links.nth(2).click() wait_for_app_run(app) # Verify content updated - be specific expect(app.get_by_test_id("stHeading").filter(has_text="Page 3")).to_be_visible() def test_overflow_behavior(app: Page): """Test overflow menu when too many pages for viewport.""" # Enable overflow test mode click_checkbox(app, "Test Overflow (5 pages)") wait_for_app_run(app) # Set medium viewport that might trigger overflow app.set_viewport_size({"width": 800, "height": 600}) # Verify we have 5 nav links total nav_links = app.get_by_test_id("stTopNavLink") expect(nav_links).to_have_count(5) # Note: Due to our mock of rc-overflow in the JS tests, all links will be visible # In real implementation, some would be hidden and overflow menu would appear # Check that the overflow container exists overflow_items = app.locator(".rc-overflow-item") expect(overflow_items.first).to_be_visible() def test_top_nav_with_sections(app: Page): """Test top navigation with section headers.""" app.set_viewport_size({"width": 1280, "height": 800}) # Enable sections test mode click_checkbox(app, "Test Sections") wait_for_app_run(app) # When sections are used, section names become the top-level nav items # Verify sections are rendered as clickable items section_a_trigger = app.get_by_text("Section A").first section_b_trigger = app.get_by_text("Section B").first expect(section_a_trigger).to_be_visible() expect(section_b_trigger).to_be_visible() # Click section A to open dropdown/popover section_a_trigger.click() # Wait for pages to become visible after clicking section page1_in_popover = app.get_by_role("link", name="Page 1") page2_in_popover = app.get_by_role("link", name="Page 2") expect(page1_in_popover).to_be_visible() expect(page2_in_popover).to_be_visible() # Click a page in the popover page2_in_popover.click() wait_for_app_run(app) # Verify navigation worked - check the header expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() def test_top_nav_with_single_section(app: Page): """Test top navigation with a single section containing 3 pages.""" app.set_viewport_size({"width": 1280, "height": 800}) # Enable single section test mode click_checkbox(app, "Test Single Section (3 pages)") wait_for_app_run(app) # When a single section is used, the section name should be in the top nav section_trigger = app.get_by_text("My Section").first expect(section_trigger).to_be_visible() # Click the section to open dropdown/popover section_trigger.click() # Wait for all 3 pages to become visible in the popover page1_in_popover = app.get_by_role("link", name="Page 1") page2_in_popover = app.get_by_role("link", name="Page 2") page3_in_popover = app.get_by_role("link", name="Page 3") expect(page1_in_popover).to_be_visible() expect(page2_in_popover).to_be_visible() expect(page3_in_popover).to_be_visible() # Navigate to page 3 to verify navigation works page3_in_popover.click() wait_for_app_run(app) # Verify navigation worked - check the header expect(app.get_by_test_id("stHeading").filter(has_text="Page 3")).to_be_visible() # Click the section again to verify it still works after navigation section_trigger.click() # Verify pages are still accessible expect(page1_in_popover).to_be_visible() # Navigate back to page 1 page1_in_popover.click() wait_for_app_run(app) # Verify we're back on page 1 expect(app.get_by_test_id("stHeading").filter(has_text="Page 1")).to_be_visible() def test_top_nav_section_headers_support_markdown(app: Page): """Test that top nav section headers render markdown formatting.""" app.set_viewport_size({"width": 1280, "height": 800}) # Enable markdown section headers test mode click_checkbox(app, "Test Markdown Section Headers") wait_for_app_run(app) # Verify bold rendering for "**Bold** Section" bold_section_trigger = app.get_by_text("Bold Section").first expect(bold_section_trigger).to_be_visible() expect(bold_section_trigger.locator("strong")).to_have_text("Bold") # Verify italic rendering for "*Italic* Section" italic_section_trigger = app.get_by_text("Italic Section").first expect(italic_section_trigger).to_be_visible() expect(italic_section_trigger.locator("em")).to_have_text("Italic") # Verify material icon rendering for ":material/settings: Icon Section" icon_section_trigger = app.get_by_text("Icon Section").first expect(icon_section_trigger).to_be_visible() # The StreamlitMarkdown component renders material icons as <span role="img"> expect( icon_section_trigger.get_by_role("img", name="settings icon") ).to_be_visible() # Test that clicking a markdown section opens its popover correctly bold_section_trigger.click() # Wait for popover with pages page1_in_popover = app.get_by_role("link", name="Page 1") page2_in_popover = app.get_by_role("link", name="Page 2") expect(page1_in_popover).to_be_visible() expect(page2_in_popover).to_be_visible() # Navigate to verify functionality page2_in_popover.click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() def test_hidden_navigation_mode(app: Page): """Test hidden navigation mode.""" app.set_viewport_size({"width": 1280, "height": 800}) # Enable hidden navigation mode click_checkbox(app, "Test Hidden Navigation") wait_for_app_run(app) # No sidebar should be visible expect(app.get_by_test_id("stSidebar")).not_to_be_visible() # No nav links should be visible expect(app.get_by_test_id("stTopNavLink")).not_to_be_visible() # Only first page content should be visible - check header expect(app.get_by_test_id("stHeading").filter(has_text="Page 1")).to_be_visible() def test_switching_navigation_modes(app: Page): """Test dynamically switching between navigation modes.""" app.set_viewport_size({"width": 1280, "height": 800}) # Enable navigation switching mode click_checkbox(app, "Test Navigation Switching") wait_for_app_run(app) # Initially should show sidebar (default) expect(app.get_by_test_id("stSidebar")).to_be_visible() # Navigate to page 2 first to test state persistence sidebar_links = app.get_by_test_id("stSidebarNavLink") sidebar_links.nth(1).click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() # Click button to switch to top nav app.get_by_role("button", name="Switch to Top Nav").click() wait_for_app_run(app) # Verify switched to top nav - sidebar hidden, nav links visible at top expect(app.get_by_test_id("stSidebar")).not_to_be_visible() nav_links = app.get_by_test_id("stTopNavLink") expect(nav_links).to_have_count(3) expect(nav_links.first).to_be_visible() # Verify we're still on page 2 (state persistence) expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() # Navigation should still work in top nav mode nav_links.nth(2).click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 3")).to_be_visible() def test_top_nav_with_logo(app: Page, assert_snapshot: ImageCompareFunction): """Tests that the logo with a top navigation is shown in the correct size, even when the viewport is narrowed. """ app.set_viewport_size({"width": 1280, "height": 800}) # Enable features: click_checkbox(app, "Test Overflow (5 pages)") click_checkbox(app, "Test Sidebar Content") click_checkbox(app, "Test Logo") # Collapse sidebar app.get_by_test_id("stSidebar").hover() close_button = app.get_by_test_id("stSidebarCollapseButton") expect(close_button).to_be_visible() close_button.click() expect(app.get_by_test_id("stSidebar")).not_to_be_visible() # Wait for logo to be visible logo = app.get_by_test_id("stHeaderLogo") expect(logo).to_be_visible() # Take snapshot of the header with logo at full width header = app.locator("header").first assert_snapshot(header, name="st_navigation-top_nav_with_logo") # Test that logo size is preserved at a narrower viewport # This validates the flexShrink: 0 fix on StyledHeaderLeftSection app.set_viewport_size({"width": 800, "height": 600}) # Logo should still be visible and maintain its size expect(logo).to_be_visible() assert_snapshot(header, name="st_navigation-top_nav_with_logo_narrow_viewport") def test_top_nav_visual_regression(app: Page, assert_snapshot: ImageCompareFunction): """Visual regression test for top navigation.""" app.set_viewport_size({"width": 1280, "height": 800}) wait_for_app_run(app) # Wait for app to stabilize nav_links = app.get_by_test_id("stTopNavLink") expect(nav_links.first).to_be_visible() # Take screenshot of the navigation area # Since there's no specific top nav container, capture the header area nav_area = app.locator("header").first assert_snapshot(nav_area, name="st_navigation-top_nav_desktop") # Test hover state nav_links.first.hover() assert_snapshot(nav_area, name="st_navigation-top_nav_hover") # Test with sections click_checkbox(app, "Test Sections") wait_for_app_run(app) section_a = app.get_by_text("Section A").first expect(section_a).to_be_visible() section_a.click() # Wait for popover to appear using proper expect # The dropdown link should be visible after clicking the section dropdown_link = app.get_by_test_id("stTopNavDropdownLink").filter(has_text="Page 1") expect(dropdown_link).to_be_visible() # Get the visible popover container by its test ID # There are multiple popovers (one per section), so we need the visible one popover = app.get_by_test_id("stTopNavPopover").locator("visible=true") assert_snapshot(popover, name="st_navigation-top_nav_section_popover") # Test single section # First uncheck the Test Sections checkbox click_checkbox(app, "Test Sections") wait_for_app_run(app) # Enable single section test click_checkbox(app, "Test Single Section (3 pages)") wait_for_app_run(app) # Take screenshot of single section in nav nav_area = app.locator("header").first assert_snapshot(nav_area, name="st_navigation-top_nav_single_section") # Click the section to open popover single_section_trigger = app.get_by_text("My Section").first expect(single_section_trigger).to_be_visible() single_section_trigger.click() # Wait for popover with 3 pages page3_in_popover = app.get_by_role("link", name="Page 3") expect(page3_in_popover).to_be_visible() # Take screenshot of single section popover # Get one of the dropdown links to locate the popover container dropdown_link_in_single = app.get_by_test_id("stTopNavDropdownLink").filter( has_text="Page 1" ) expect(dropdown_link_in_single).to_be_visible() # Get the popover container by its test ID # For single section there's only one popover but we use .first for consistency single_section_popover = app.get_by_test_id("stTopNavPopover").first assert_snapshot( single_section_popover, name="st_navigation-top_nav_single_section_popover" ) def test_mixed_empty_and_named_sections(app: Page): """Test top navigation with mixed empty and named sections. This tests the issue #12243 scenario where some sections have names and some sections are empty (""). The empty section pages should appear at the top level of navigation while named sections should have dropdowns. """ app.set_viewport_size({"width": 1280, "height": 800}) # Enable mixed sections test mode click_checkbox(app, "Test Mixed Empty/Named Sections") wait_for_app_run(app) # Verify that empty section pages appear as top-level nav items home_nav = app.get_by_test_id("stTopNavLink").filter(has_text="Home") dashboard_nav = app.get_by_test_id("stTopNavLink").filter(has_text="Dashboard") expect(home_nav).to_be_visible() expect(dashboard_nav).to_be_visible() # Verify that named sections appear as section triggers admin_trigger = app.get_by_text("Admin").first reports_trigger = app.get_by_text("Reports").first expect(admin_trigger).to_be_visible() expect(reports_trigger).to_be_visible() # Click on a top-level page (from empty section) dashboard_nav.click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() # Click on Admin section to open dropdown admin_trigger.click() # Wait for Admin section pages to be visible settings_link = app.get_by_role("link", name="Settings") users_link = app.get_by_role("link", name="Users") expect(settings_link).to_be_visible() expect(users_link).to_be_visible() # Navigate to Settings page settings_link.click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 3")).to_be_visible() # Click on Reports section reports_trigger.click() # Verify Reports section has only one page analytics_link = app.get_by_role("link", name="Analytics") expect(analytics_link).to_be_visible() # Navigate to Analytics analytics_link.click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 5")).to_be_visible() # Navigate back to a top-level page to verify mixed navigation still works home_nav.click() wait_for_app_run(app) expect(app.get_by_test_id("stHeading").filter(has_text="Page 1")).to_be_visible() def test_mixed_sections_visual_regression( app: Page, assert_snapshot: ImageCompareFunction ): """Visual regression test for mixed empty and named sections navigation. Verifies the visual appearance of top navigation when configuration includes both empty sections (pages at top level) and named sections (with dropdowns). Tests navigation bar rendering, dropdown popovers, and hover states. """ app.set_viewport_size({"width": 1280, "height": 800}) # Enable mixed sections test mode click_checkbox(app, "Test Mixed Empty/Named Sections") wait_for_app_run(app) # Wait for navigation to stabilize home_nav = app.get_by_test_id("stTopNavLink").filter(has_text="Home") expect(home_nav).to_be_visible() # Take screenshot of mixed navigation bar nav_area = app.locator("header").first assert_snapshot(nav_area, name="st_navigation-mixed_sections_nav_bar") # Open Admin dropdown and capture popover admin_trigger = app.get_by_text("Admin").first admin_trigger.click() # Wait for dropdown to open settings_link = app.get_by_role("link", name="Settings") expect(settings_link).to_be_visible() # Capture Admin section popover admin_popover = app.get_by_test_id("stTopNavPopover").locator("visible=true") assert_snapshot(admin_popover, name="st_navigation-mixed_sections_admin_popover") # Close Admin dropdown by clicking elsewhere app.get_by_test_id("stMain").click() # Open Reports dropdown reports_trigger = app.get_by_text("Reports").first reports_trigger.click() # Wait for Reports dropdown analytics_link = app.get_by_role("link", name="Analytics") expect(analytics_link).to_be_visible() # Capture Reports section popover (single item) reports_popover = app.get_by_test_id("stTopNavPopover").locator("visible=true") assert_snapshot( reports_popover, name="st_navigation-mixed_sections_reports_popover" ) # Test hover state on mixed navigation home_nav.hover() assert_snapshot(nav_area, name="st_navigation-mixed_sections_hover_home") # Hover on a section trigger admin_trigger.hover() assert_snapshot(nav_area, name="st_navigation-mixed_sections_hover_admin") def test_mobile_sidebar_overlay_visual( app: Page, assert_snapshot: ImageCompareFunction ): """Visual regression test for mobile sidebar overlay behavior.""" # Set mobile viewport app.set_viewport_size({"width": 375, "height": 667}) wait_for_app_run(app) # On mobile with AUTO state, sidebar should be collapsed by default sidebar = app.get_by_test_id("stSidebar") expect(sidebar).to_have_attribute("aria-expanded", "false") # Take screenshot of initial collapsed state assert_snapshot(app, name="st_navigation-mobile_sidebar_overlay_collapsed") # Expand the sidebar to test overlay behavior expand_button = app.get_by_test_id("stExpandSidebarButton") expand_button.click() # Wait for sidebar to expand and verify navigation is visible expect(sidebar).to_have_attribute("aria-expanded", "true") nav_links = app.get_by_test_id("stSidebarNavLink") expect(nav_links).to_have_count(3) expect(nav_links.first).to_be_visible() # Take screenshot showing sidebar overlaying content # Capture the entire viewport to show overlay effect assert_snapshot(app, name="st_navigation-mobile_sidebar_overlay_expanded") # Test collapsed sidebar state # Click the close button to collapse sidebar close_button = app.get_by_test_id("stSidebarCollapseButton") close_button.click() # Wait for sidebar to collapse # The sidebar aria-expanded attribute should be false expect(sidebar).to_have_attribute("aria-expanded", "false") # Test navigation interaction # Expand sidebar again using the expand button in the header expand_button = app.get_by_test_id("stExpandSidebarButton") expand_button.click() # Wait for sidebar to expand expect(sidebar).to_have_attribute("aria-expanded", "true") expect(nav_links.first).to_be_visible() # Navigate to a different page nav_links.nth(1).click() wait_for_app_run(app) # Verify navigation worked and content updated behind sidebar expect(app.get_by_test_id("stHeading").filter(has_text="Page 2")).to_be_visible() # Take screenshot showing different page content with sidebar overlay assert_snapshot(app, name="st_navigation-mobile_sidebar_overlay_page2") # Test with sections enabled on mobile # First collapse sidebar to access the checkbox close_button = app.get_by_test_id("stSidebarCollapseButton") close_button.click() expect(sidebar).to_have_attribute("aria-expanded", "false") # Now click the Test Sections checkbox click_checkbox(app, "Test Sections") wait_for_app_run(app) # Expand sidebar to see sections expand_button = app.get_by_test_id("stExpandSidebarButton") expand_button.click() expect(sidebar).to_have_attribute("aria-expanded", "true") # Verify sections are rendered in sidebar on mobile section_a = app.get_by_text("Section A").first expect(section_a).to_be_visible() # Take screenshot of sections in mobile sidebar assert_snapshot(sidebar, name="st_navigation-mobile_sidebar_sections") # ===== TOP PADDING VISUAL REGRESSION TESTS ===== # These tests validate the top padding logic in frontend/app/src/components/AppView/styled-components.ts # which sets different top padding values based on embedded mode, toolbar visibility, and navigation presence: # - 2.25rem: embedded minimal (no header, no toolbar) # - 4.5rem: embedded with header but no toolbar # - 6rem: non-embedded default OR embedded with show_toolbar # - 8rem: non-embedded with top navigation present def test_top_padding_visual_regression_embedded_modes( app: Page, assert_snapshot: ImageCompareFunction ): """Visual regression test for top padding in different embedded modes. Tests the top padding logic from styled-components.ts: - 2.25rem: embedded minimal (no header, no toolbar) - 4.5rem: embedded with header but no toolbar - 6rem: embedded with show_toolbar """ app.set_viewport_size({"width": 1280, "height": 800}) wait_for_app_run(app) # Get the current URL for embedding tests current_url = app.url base_url = current_url.split("?")[0] # Test 1: Embedded minimal mode (2.25rem) - enable hidden nav first to remove headers click_checkbox(app, "Test Hidden Navigation") wait_for_app_run(app) goto_app(app, f"{base_url}?embed=true") wait_for_app_run(app) # Should have minimal UI - this triggers the 2.25rem padding case main_content = app.get_by_test_id("stMain") expect(main_content).to_be_visible() assert_snapshot(main_content, name="st_app_top_padding-embedded_minimal_2_25rem") # Test 2: Embedded with toolbar (6rem) goto_app(app, f"{base_url}?embed=true&show_toolbar=true") wait_for_app_run(app) # Should show toolbar, triggering 6rem padding assert_snapshot(main_content, name="st_app_top_padding-embedded_with_toolbar_6rem") # Test 3: Go back to normal mode and test embedded with header (4.5rem) goto_app(app, base_url) wait_for_app_run(app) # Uncheck hidden navigation to enable normal page headers click_checkbox(app, "Test Hidden Navigation") # This unchecks it wait_for_app_run(app) goto_app(app, f"{base_url}?embed=true") wait_for_app_run(app) # Should have headers but no toolbar, triggering 4.5rem padding assert_snapshot(main_content, name="st_app_top_padding-embedded_with_header_4_5rem") def test_top_padding_visual_regression_non_embedded_modes( app: Page, assert_snapshot: ImageCompareFunction ): """Visual regression test for top padding in non-embedded modes. Tests the top padding logic from styled-components.ts: - 6rem: non-embedded default (no top nav) - 8rem: non-embedded with top nav (when navigation is present) """ app.set_viewport_size({"width": 1280, "height": 800}) wait_for_app_run(app) main_content = app.get_by_test_id("stMain") expect(main_content).to_be_visible() # Test 1: Non-embedded default (6rem) - enable hidden navigation to remove top nav click_checkbox(app, "Test Hidden Navigation") wait_for_app_run(app) # Should have 6rem padding when no top nav is present assert_snapshot(main_content, name="st_app_top_padding-non_embedded_default_6rem") # Test 2: Non-embedded with top nav (8rem) - disable hidden navigation click_checkbox(app, "Test Hidden Navigation") # This unchecks it wait_for_app_run(app) # Should have 8rem padding when top nav is present (if navigation works) # Note: This test may capture the state regardless of whether nav links are visible assert_snapshot( main_content, name="st_app_top_padding-non_embedded_with_top_nav_8rem" ) def test_top_padding_mobile_responsive_behavior( app: Page, assert_snapshot: ImageCompareFunction ): """Test top padding behavior on mobile viewports.""" # Mobile view app.set_viewport_size({"width": 375, "height": 667}) wait_for_app_run(app) main_content = app.get_by_test_id("stMain") expect(main_content).to_be_visible() # Mobile should have different top padding since navigation behavior changes assert_snapshot(main_content, name="st_app_top_padding-mobile_responsive") # Test embedded mobile as well current_url = app.url base_url = current_url.split("?")[0] goto_app(app, f"{base_url}?embed=true") wait_for_app_run(app) assert_snapshot(main_content, name="st_app_top_padding-mobile_embedded")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/multipage_apps_v2/mpa_v2_top_nav_test.py", "license": "Apache License 2.0", "lines": 527, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/theme_from_window.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from theme_tester_app import run_theme_tester_app # type: ignore run_theme_tester_app()
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/theme_from_window.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/theme_from_window_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction, wait_for_app_loaded from e2e_playwright.shared.app_utils import expect_font, expect_no_skeletons def test_theme_from_window_variable(app: Page, assert_snapshot: ImageCompareFunction): # Inject custom theme configuration script app.add_init_script(""" window.__streamlit = { LIGHT_THEME: { base: "light", primaryColor: "#1a6ce7", secondaryBackgroundColor: "#f7f7f7", textColor: "#1e252f", borderColor: "#d5dae4", showWidgetBorder: true, bodyFont: "Inter", headingFont: "Inter", codeFont: '"Monaspace Argon", Menlo, Monaco, Consolas, "Courier New", monospace', baseFontSize: 14, fontFaces: [ { family: "Inter", url: "./app/static/Inter-Regular.woff2", weight: 400, }, { family: "Inter", url: "./app/static/Inter-SemiBold.woff2", weight: 600, }, { family: "Inter", url: "./app/static/Inter-Bold.woff2", weight: 700, }, { family: "Inter", url: "./app/static/Inter-Black.woff2", weight: 900, }, { "family": "Monaspace Argon", "url": "https://raw.githubusercontent.com/githubnext/monaspace/refs/heads/main/fonts/webfonts/MonaspaceArgon-Regular.woff2", "weight": 400, }, { "family": "Monaspace Argon", "url": "https://raw.githubusercontent.com/githubnext/monaspace/refs/heads/main/fonts/webfonts/MonaspaceArgon-Medium.woff2", "weight": 500, }, { "family": "Monaspace Argon", "url": "https://raw.githubusercontent.com/githubnext/monaspace/refs/heads/main/fonts/webfonts/MonaspaceArgon-Bold.woff2", "weight": 700, }, ], } } """) app.reload() wait_for_app_loaded(app) # Make sure that all elements are rendered and no skeletons are shown: expect_no_skeletons(app, timeout=25000) # Add some additional timeout to ensure that fonts can load without # creating flakiness: app.wait_for_timeout(5000) expect_font(app, "Inter") expect_font(app, "Monaspace Argon") app.wait_for_timeout(5000) assert_snapshot(app, name="theme_from_window_variable")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/theme_from_window_test.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/font_unicode_range_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_font, expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_tagesschrift_font(): """Configure Tagesschrift font with basic and extended latin characters.""" os.environ["STREAMLIT_THEME_FONT_FACES"] = json.dumps( [ { "family": "Tagesschrift", "url": "./app/static/Tagesschrift-basic-latin.woff2", "weight": 400, "style": "normal", "unicode_range": ( "U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, " "U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, " "U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD" ), }, { "family": "Tagesschrift", "url": "./app/static/Tagesschrift-extended-latin.woff2", "weight": 400, "style": "normal", "unicode_range": ( "U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, " "U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, " "U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF" ), }, { "family": "Chimera", "url": "./app/static/NotoSans-only-letters_and_numbers.woff2", "unicode_range": "U+0000-0040", }, { "family": "Chimera", "url": "./app/static/SourGummy-Normal-Variable.ttf", "unicode_range": "U+0041-10FFFF", }, ] ) os.environ["STREAMLIT_THEME_FONT"] = ( '"Tagesschrift", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif' ) os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] = ( '"Chimera", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif' ) os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] = "16" os.environ["STREAMLIT_CLIENT_TOOLBAR_MODE"] = "minimal" yield del os.environ["STREAMLIT_THEME_FONT_FACES"] del os.environ["STREAMLIT_THEME_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] del os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] del os.environ["STREAMLIT_CLIENT_TOOLBAR_MODE"] @pytest.mark.usefixtures("configure_tagesschrift_font") def test_font_unicode_ranges(app: Page, assert_snapshot: ImageCompareFunction): # Make sure that all elements are rendered and no skeletons are shown expect_no_skeletons(app, timeout=25000) # Verify Tagesschrift font is loaded expect_font(app, "Tagesschrift") # Verify Chimera font is loaded expect_font(app, "Chimera") assert_snapshot(app, name="font_unicode_range-font_unicode_ranges")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/font_unicode_range_test.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
streamlit/streamlit:e2e_playwright/theming/font_weight.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import streamlit as st st.set_page_config(initial_sidebar_state="expanded") st.header("SourGummy Font Test") # Test the variable font files with string weight ranges with st.container(key="weight_ranges_variable_font"): st.markdown("This is normal text with numbers 0123456789.") st.markdown("*This is italic text with numbers 0123456789.*") st.markdown("**This is bold text with numbers 0123456789.**") st.markdown("***This is bold-italic text with numbers 0123456789.***") # Test the static font files with string and integer weights with st.sidebar.container(key="numeric_string_weight"): st.markdown("This is normal text rendered as normal-thin.") with st.sidebar.container(key="normal_string_weight"): st.markdown("*This is italic text rendered as normal-light.*") with st.sidebar.container(key="integer_weight"): st.markdown("**This is bold text rendered as normal-semibold.**") with st.sidebar.container(key="bold_string_weight"): st.markdown("***This is bold-italic text rendered as normal-black.***")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/font_weight.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
streamlit/streamlit:e2e_playwright/theming/font_weight_test.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import pytest from playwright.sync_api import Page from e2e_playwright.conftest import ImageCompareFunction from e2e_playwright.shared.app_utils import expect_font, expect_no_skeletons @pytest.fixture(scope="module") @pytest.mark.early def configure_sour_gummy_font(): """Configure Sour Gummy font.""" os.environ["STREAMLIT_THEME_FONT_FACES"] = json.dumps( [ { "family": "SourGummy", "url": "./app/static/SourGummy-Normal-Variable.ttf", "weight": "100 900", "style": "normal", }, { "family": "SourGummy", "url": "./app/static/SourGummy-Italic-Variable.ttf", "weight": "100 900", "style": "italic", }, { "family": "SourGummyExtreme", "url": "./app/static/SourGummy-Thin.ttf", "weight": "400", "style": "normal", }, { "family": "SourGummyExtreme", "url": "./app/static/SourGummy-SemiBold.ttf", "weight": 700, "style": "normal", }, { "family": "SourGummyExtreme", "url": "./app/static/SourGummy-Light.ttf", "weight": "normal", "style": "italic", }, { "family": "SourGummyExtreme", "url": "./app/static/SourGummy-Black.ttf", "weight": "bold", "style": "italic", }, ] ) os.environ["STREAMLIT_THEME_FONT"] = ( '"SourGummy", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif' ) os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] = ( '"SourGummyExtreme", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif' ) os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] = "16" os.environ["STREAMLIT_CLIENT_TOOLBAR_MODE"] = "minimal" yield del os.environ["STREAMLIT_THEME_FONT_FACES"] del os.environ["STREAMLIT_THEME_FONT"] del os.environ["STREAMLIT_THEME_SIDEBAR_FONT"] del os.environ["STREAMLIT_THEME_BASE_FONT_SIZE"] del os.environ["STREAMLIT_CLIENT_TOOLBAR_MODE"] @pytest.mark.usefixtures("configure_sour_gummy_font") def test_font_weights(app: Page, assert_snapshot: ImageCompareFunction): # Make sure that all elements are rendered and no skeletons are shown expect_no_skeletons(app, timeout=25000) # Verify SourGummy font is loaded expect_font(app, "SourGummy", style="normal") expect_font(app, "SourGummy", style="italic") # Verify SourGummyExtreme font is loaded expect_font(app, "SourGummyExtreme", style="normal", weight="normal") expect_font(app, "SourGummyExtreme", style="normal", weight="bold") expect_font(app, "SourGummyExtreme", style="italic", weight="normal") expect_font(app, "SourGummyExtreme", style="italic", weight="bold") assert_snapshot(app, name="font_weight-font_weights")
{ "repo_id": "streamlit/streamlit", "file_path": "e2e_playwright/theming/font_weight_test.py", "license": "Apache License 2.0", "lines": 90, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test