repo_id
stringclasses 1
value | file_path
stringlengths 16
121
| content
stringlengths 4
160k
| token_count
int64 3
66.1k
|
|---|---|---|---|
streamlit
|
streamlit/.claude/hooks/pre_bash_redirect.py
|
#!/usr/bin/env python3
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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():
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 commands instead:\n"
f" - Run 'make help' to see available targets\n"
f" - Use 'make run-e2e-test <filename>' for e2e tests\n",
file=sys.stderr,
)
sys.exit(2)
sys.exit(0)
if __name__ == "__main__":
main()
| 1,195
|
streamlit
|
streamlit/.claude/settings.json
|
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/pre_bash_redirect.py",
"timeout": 10
}
]
}
]
}
}
| 178
|
streamlit
|
streamlit/.cursor/commands/py-docstring-fix.md
|
# Python Docstrings - Fix
## Overview
Add or correct Numpydoc-style docstrings for public modules, classes, functions, and methods without changing code behavior.
Refer to the Docstrings guidance in `.cursor/rules/python.mdc`.
## Success Criteria
- All public APIs have clear, accurate Numpydoc docstrings.
- Module-level docstrings exist for user-facing modules.
- Parameter names, types, defaults, and behavior align with the implementation and type hints.
- Relevant exceptions are documented in a `Raises` section.
- Nontrivial functions/classes include a minimal, runnable `Examples` section.
- `make python-lint` and `make python-tests` pass.
## What to do
1. Discover targets
- Find public callables and classes missing docstrings or with incomplete/incorrect content.
- Add module-level docstrings where users are expected to import from the module.
2. Write/repair docstrings (Numpydoc)
- Start with a one-sentence summary line (imperative mood), followed by a short paragraph if useful.
- Common sections to use:
- `Parameters`: names, types, and concise descriptions; include defaults (e.g., `float, default=1e-9`).
- `Returns` or `Yields`: type and meaning; describe shape/units if applicable.
- `Raises`: list exceptions and the conditions that trigger them.
- `Examples`: simple doctest-style examples for nontrivial behavior.
- Optionally: `See Also`, `Notes`, `Warnings` for important context.
- For classes, document constructor arguments in the class docstring rather than `__init__`.
- Keep terminology consistent with code; align with type hints and actual behavior.
3. Validate
- Ensure no code behavior or signatures change.
- Run `make python-lint` and `make python-tests` and fix any issues.
## Do not
- Modify production logic, public APIs, or test behavior.
- Reformat unrelated code.
- Add speculative sections (e.g., `Raises`) that do not reflect actual behavior.
## Example (format only)
```python
def normalize(values: Sequence[float], *, epsilon: float = 1e-9) -> list[float]:
"""Normalize values so they sum to 1.
Parameters
----------
values : Sequence[float]
Input numbers; must be finite and non-empty.
epsilon : float, default=1e-9
Small constant to avoid division by zero.
Returns
-------
list[float]
Normalized weights summing to 1.
Raises
------
ValueError
If `values` is empty or contains non-finite numbers.
Examples
--------
>>> normalize([1, 1, 2])
[0.25, 0.25, 0.5]
"""
```
## Checklist
[ ] Public modules/classes/functions/methods documented with Numpydoc.
[ ] Module-level docstrings added where applicable.
[ ] Parameter names, types, and defaults aligned with code and hints.
[ ] Relevant exceptions listed in `Raises`.
[ ] Examples added for nontrivial APIs.
[ ] `make python-lint` and `make python-tests` pass.
| 883
|
streamlit
|
streamlit/.cursor/commands/py-parameterize-test.md
|
# Parameterize Tests
## Overview
Convert repetitive `pytest` tests into parameterized tests using `pytest.mark.parametrize` to reduce duplication and improve maintainability, without changing behavior or reducing test coverage.
## Success Criteria
- Coverage is maintained or increased.
- All tests pass via `pytest`.
- Each new or updated test includes a brief numpydoc-style docstring.
- Provide meaningful `ids` for parameter sets to aid readability.
- Preserve existing markers and fixtures; use `pytest.param(..., marks=...)` for case-specific marks (e.g., `xfail`, `skip`).
## What to do
1. Discover candidates
- Identify tests that only vary input values, expected outputs, or expected exceptions.
- Include existing edge and boundary cases; do not remove unique scenarios.
2. Design parameters
- Choose clear argument names and create tuples for each case.
- Use `pytest.param` when individual cases require marks.
- Add `ids=[...]` for stable, human-readable case names.
3. Implement
- Replace duplicated tests with a single parameterized test.
- Keep the assertion logic equivalent; do not change runtime behavior.
- Deduplicate or promote fixtures only if they are reused (2+ call sites); otherwise keep them local.
4. Validate
- Run `pytest` on applicable files and ensure all tests pass.
- If grouping introduces ambiguity or flakiness, split or adjust the parameterization.
## Do not
- Modify production (non-test) code.
- Remove or weaken unique test scenarios.
- Over-parameterize when it reduces readability or obscures intent.
## Checklist
[ ] Parameterizable tests consolidated with `pytest.mark.parametrize`.
[ ] All tests pass (`pytest`).
[ ] Coverage maintained or increased.
[ ] Brief numpydoc docstring on new/updated tests.
[ ] Meaningful `ids` added; per-case marks preserved with `pytest.param`.
| 493
|
streamlit
|
streamlit/.cursor/rules/e2e_playwright.mdc
|
---
description:
globs: e2e_playwright/**/*.py
alwaysApply: false
---
# Streamlit E2E Tests
We use playwright with pytest to e2e test Streamlit library. E2E tests verify the complete Streamlit system (frontend, backend, communication, state, visual appearance) from a user's perspective (black-box). They complement Python/JS unit tests, which are faster and focus on internal logic, input/output validation, and specific message sequences. Use E2E tests when testing behavior that requires the full stack or visual verification, especially for new elements or significant changes to existing ones.
## Test Structure
- Located in `e2e_playwright/`
- Each test consists of two files:
- `*.py`: Streamlit app script that's being tested
- `*_test.py`: Playwright pytest file that runs the app and tests it
- If the test is specific to a Streamlit element, prefix the filename with `st_<element_name>`
- Tests can use screenshot comparisons for visual verification
- All screenshots are stored in `e2e_playwright/__snapshots__/<os>/`
- Other e2e test results are stored in `e2e_playwright/test_results/` which includes:
- `e2e_playwright/test_results/<test_name>/`: Video and traces related to the failed test.
- `e2e_playwright/test_results/snapshot-tests-failures/<os>/<test_script>/<test_name>/`: Expected, actual, and diff screenshots of the failed snapshot test.
- `e2e_playwright/test_results/snapshot-updates/<os>/<test_script>/<test_name>/`: All updated screenshots of the failed test.
## Key Fixtures and Utilities
Import from `conftest.py`:
- `app: Page` - Light mode app fixture
- `themed_app: Page` - Light & dark mode app fixture
- `assert_snapshot` - Screenshot testing fixture. Ensure element is stable before calling.
- `wait_for_app_run(app)` - Wait for app run to finish
- `wait_for_app_loaded(app)` - Wait for initial app load
- `rerun_app(app)` - Trigger app rerun and wait
- `wait_until(app, fn)` - Run test function until True or timeout
## Best Practices
- As a guiding principle, tests should resemble how users interact with the UI.
- Use `expect` for auto-wait assertions, not `assert` (reduces flakiness)
- If `expect` is insufficient, use the `wait_until` utility. Never use `wait_for_timeout`.
- Prefer label- or key-based locators over index-based access (e.g. `get_by_test_id().nth(0)`). The recommended order of priority is:
1. get elements by label (see `app_utils` methods, e.g. `get_text_input`).
2. elements that don't support `label` but support `key`: get elements by a unique key (`get_element_by_key`).
3. If the element doesn't support key or label, you can wrap it with an `st.container(key="my_key")` to better target it via `get_element_by_key`. E.g. `get_element_by_key("my_key").get_by_test_id("stComponent")`.
- Prefer stable locators like `get_by_test_id`, `get_by_text` or `get_by_role` over CSS / XPath selectors via `.locator`.
- Group related tests into single, logical test files (e.g., by widget or feature) for CI efficiency.
- Minimize screenshot surface area; screenshot specific elements, not the whole page unless necessary.
- Use descriptive test names.
- Ensure elements screenshotted are under 640px height to avoid clipping by the header.
- Naming convention for command-related snapshots: `st_command-test_description`
- Take a look at other tests in `e2e_playwright/` as inspiration.
- e2e tests are expensive, please test every aspect only one time.
- Make use of shared `app_utils` methods (import from `e2e_playwright.shared.app_utils`) if applicable.
- Make sure that the tests mix different ways of interactions (e.g. fill and type for input fields) for increased coverage.
## Writing Tests & Common Scenarios
When adding or modifying tests for an element, ensure the following are covered:
- **Visuals:** Snapshot tests for both normal and `disabled` states.
- **Interactivity:** Test user interactions and verify the resulting app state or output (e.g., checking text written via `st.write`, potentially using helpers like `expect_markdown` from `shared/app_utils.py`).
- **Common Contexts:** Verify behavior within:
- A `@st.fragment`.
- An `st.form`.
- **Core Behavior:**
- State persistence (widget value is retained) if the element is temporarily unmounted and remounted.
- The element cannot be interacted with when `disabled=True`.
- If the element uses the `help` parameter, verify the tooltip appears correctly on hover.
- If the element uses the `key` parameter, verify a corresponding CSS class or attribute is set.
- If the element is a widget, make sure to test that the identity is kept stable when `key` is provided.
- **Custom Config:** Use module-scoped fixtures with `@pytest.mark.early` for tests requiring specific Streamlit configuration options.
## Running tests
- Single test: `make run-e2e-test e2e_playwright/name_of_the_test.py`
- Debug test (needs manual interactions): `make debug-e2e-test e2e_playwright/name_of_the_test.py`
- If frontend logic was changed, it will require running `make frontend-fast` to update the frontend.
- You can ignore missing or mismatched snapshot errors. These need to be updated manually.
| 1,471
|
streamlit
|
streamlit/.cursor/rules/make_commands.mdc
|
---
description: List of all available make commands
globs:
alwaysApply: false
---
# Available `make` commands
List of all `make` commands that are available for execution from the repository root folder:
help Show all available make commands.
all Install all dependencies, build frontend, and install editable Streamlit.
all-dev Install all dependencies and editable Streamlit, but do not build the frontend.
init Install all dependencies and build protobufs.
clean Remove all generated files.
protobuf Recompile Protobufs for Python and the frontend.
python-init Install Python dependencies and Streamlit in editable mode.
python-lint Lint and check formatting of Python files.
python-format Format Python files.
python-tests Run Python unit tests.
python-performance-tests Run Python performance tests.
python-integration-tests Run Python integration tests. Requires `integration-requirements.txt` to be installed.
python-types Run the Python type checker.
frontend-init Install all frontend dependencies.
frontend Build the frontend.
frontend-with-profiler Build the frontend with the profiler enabled.
frontend-fast Build the frontend (as fast as possible).
frontend-dev Start the frontend development server.
frontend-lint Lint and check formatting of frontend files.
frontend-types Run the frontend type checker.
frontend-format Format frontend files.
frontend-tests Run frontend unit tests and generate coverage report.
frontend-typesync Check for unsynced frontend types.
update-frontend-typesync Installs missing typescript typings for dependencies.
update-snapshots Update e2e playwright snapshots based on the latest completed CI run.
update-snapshots-changed Update e2e playwright snapshots of changed e2e files based on the latest completed CI run.
update-material-icons Update material icons based on latest Google material symbol version.
update-emojis Update emojis based on latest emoji version.
update-notices Update the notices file (licenses of frontend assets and dependencies).
update-headers Update all license headers.
update-min-deps Update minimum dependency constraints file.
debug-e2e-test Run a playwright e2e test in debug mode. Use it via `make debug-e2e-test st_command_test.py`.
run-e2e-test Run a playwright e2e test. Use it via `make run-e2e-test st_command_test.py`.
trace-e2e-test Run e2e test with tracing and view it. Use via `make trace-e2e-test <test_file.py>::<test_func>`.
lighthouse-tests Run Lighthouse performance tests.
bare-execution-tests Run all e2e tests in bare mode.
cli-smoke-tests Run CLI smoke tests.
autofix Autofix linting and formatting errors.
package Create Python wheel files in `dist/`.
conda-package Create conda distribution files.
| 1,161
|
streamlit
|
streamlit/.cursor/rules/new_feature.mdc
|
---
description: Implementation guide for new features
globs:
alwaysApply: false
---
# New Feature - Implementation Guide
- Most features need to be implemented in the backend in `lib/streamlit/`, the frontend `frontend/` and will need changes to our protobuf definitions in `proto/`.
- New features should be covered by Python Unit Tests in `lib/tests`, Vitest Unit Tests, and e2e playwright tests in `e2e_playwright/`.
- Implementing new element commands requires additional steps to correctly register the element (see notes below).
## Order of implementation
1. implement protobuf changes in `proto/` & run: `make protobuf` (-> @protobuf.mdc)
- Note: new elements need to be added to `proto/streamlit/proto/Element.proto`.
2. implement backend implementation in `lib/streamlit/` (-> @python_lib.mdc)
- Note: new elements need to be added to `lib/streamlit/__init__.py`
3. implement Python unit tests in `lib/tests` & run via: `PYTHONPATH=lib pytest lib/tests/streamlit/the_test_name.py` (-> @python_tests.mdc)
- Note: new elements need to be added to `lib/tests/streamlit/element_mocks.py`
4. implement frontend changes in `frontend/` (-> @typescript.mdc)
- Note: new elements need to be added to `frontend/lib/src/components/core/Block/ElementNodeRenderer.tsx`
5. implement vitest unit tests in `*.test.tsx` & run via: `cd frontend && yarn vitest lib/src/components/elements/NewElement/NewElement.test.tsx` (-> @typescript_tests.mdc)
6. implement e2e playwright test in `e2e_playwright/` & run via: `make run-e2e-test e2e_playwright/name_of_the_test.py` (-> @e2e_playwright.mdc)
7. run `make autofix` to auto-fix linting and formatting issues.
| 534
|
streamlit
|
streamlit/.cursor/rules/overview.mdc
|
---
description:
globs:
alwaysApply: true
---
# Streamlit Repo Overview
Streamlit is an open-source (Apache 2.0) Python library for creating interactive web applications and dashboards with focus on data apps and internal tools.
## Tech Stack
- **Backend (Server):** Python, Tornado server, pytest
- **Frontend (Web UI):** TypeScript, React, Emotion (CSS-in-JS), Vite, Vitest
- **Communication:** Protocol Buffers (protobuf) over WebSocket.
## Folder Structure
- `lib/`: All backend code and assets.
- `streamlit/`: The main Streamlit library package.
- `streamlit/elements/`: Backend code of elements and widgets.
- `streamlit/runtime/`: App runtime and execution logic.
- `streamlit/web/`: Web server and CLI implementation
- `tests`: Python unit tests (pytest).
- `frontend/`: All frontend code and assets.
- `app/`: Streamlit application UI.
- `lib/`: Shared TypeScript library that contains elements, widgets, and layouts.
- `connection/`: WebSocket connection handling logic.
- `utils/`: Shared utilities.
- `proto/streamlit/proto/`: Protobuf definitions for client-server communication.
- `e2e_playwright/`: E2E tests using playwright (via pytest).
- `scripts/`: Utility scripts for development and CI/CD.
- `component-lib/`: Library for building Streamlit custom components.
- `.github/workflows/`: GitHub Actions workflows used for CI/CD.
### Shell & Build Policy (AI Agents)
- Prefer `make` targets for all dev tasks (tests, lint, format, builds).
- For Python unit tests: `pytest` commands are allowed and encouraged for running specific tests during development.
- For E2E tests: `pytest` commands targeting `e2e_playwright/` files are blocked by policy.
Use `make run-e2e-test <filename>` instead.
## `make` commands
Selection of `make` commands for development (run in the repo root):
- `help`: Show all available make commands.
- `protobuf`: Recompile Protobufs for Python and the frontend.
- `autofix`: Autofix linting and formatting errors.
**Backend Development (Python):**
- `python-lint`: Lint and check formatting of Python files (ruff).
- `python-tests`: Run all Python unit tests (pytest).
- `python-types`: Run the Python type checker (mypy & ty).
- `python-format`: Format Python files (ruff).
**Frontend Development (TypeScript):**
- `frontend-fast`: Build the frontend (vite).
- `frontend-dev`: Start the frontend development server (hot-reload).
- `frontend-lint`: Lint and check formatting of frontend files (eslint).
- `frontend-types`: Run the TypeScript type checker (tsc).
- `frontend-format`: Format frontend files (eslint).
- `frontend-tests`: Run all frontend unit tests (vitest).
**E2E Testing (Playwright):**
- `debug-e2e-test`: Run e2e test in debug mode, via: `make debug-e2e-test st_command_test.py`.
- `run-e2e-test`: Run e2e test, via: `make run-e2e-test st_command_test.py`.
### Development Tips
- **Follow existing patterns**: Check neighboring files for conventions.
- You can use the `work-tmp` directory to store temporary files, specs, and scripts.
- If you fail to run a `make` command, remember to run it from the root / top-level directory.
- The hot-reload dev server for the frontend will be available at <http://localhost:3000>.
## Testing Strategy
- **Python Unit Tests**: Test internal behavior without frontend.
- **Frontend Unit Tests**: Test React components, hooks, and related functionality with Vitest and React Testing Library.
- **E2E Tests**: Test the entire app logic end-to-end with Playwright.
- **(Python) Type Tests**: Verify public API typing with mypy `assert_type`.
- Prefer running specific tests / test scripts for newly added tests instead the entire test suite.
| 1,097
|
streamlit
|
streamlit/.cursor/rules/protobuf.mdc
|
---
description:
globs: **/*.proto
alwaysApply: false
---
# Protobuf
Protobuf messages are used for communication between the Streamlit backend and frontend via WebSocket connections.
**Note**: Messages are "released" once shipped in any Streamlit version.
## Protobuf Compatibility
Always keep protobuf messages backwards compatible. New versions must work with older Streamlit versions.
**Incompatible changes to avoid:**
- Removing a field → Add `// DEPRECATED` comment and mark `[deprecated=true]`
- Renaming a field → Deprecate old field, add new field with next available number
- Changing field numbers → Keep all existing numbers unchanged
- Adding/removing `optional` → Deprecate and create new field
- Changing field types incompatibly → Use new field with compatible type
**Compatible changes (safe to make):**
- Adding new optional fields
- Adding comments
- Marking fields as deprecated
- Modifying/removing unreleased fields
## Compile Protobuf
Changes requiring compilation:
- Adding a field
- **Unreleased messages only:** Modifying/removing fields
Changes not requiring compilation:
- Comments and `[deprecated=true]` notation
Run this command to recompile the protobufs:
```bash
make protobuf
```
## Important Files
- `ForwardMsg.proto`: Root message used to send information from the server to the frontend/browser.
- `BackMsg.proto`: Root message sent from the browser to the server, e.g. script rerun requests.
- `NewSession.proto`: First message that is sent to the browser on every rerun.
- `Block.proto`: Contains all block types. A block is a layout container for elements (e.g. columns, tabs, popovers, etc.).
- `Element.proto`: Contains all element types. An element is a UI component.
| 461
|
streamlit
|
streamlit/.cursor/rules/python.mdc
|
---
description:
globs: **/*.py
alwaysApply: false
---
# Python Development Guide
- Supported Python versions: 3.10 - 3.14
- Docstrings: Numpy style
- Linter: Ruff 0.x (`.ruff.toml`)
- Formatter: Ruff 0.x (`.ruff.toml`)
- Type Checker: mypy 1.x (`mypy.ini`)
- Testing: pytest 8.x (`lib/pytest.ini`)
## Key Principles
- PEP 8 Compliance: Adhere to PEP 8 guidelines for code style, with Ruff as the primary linter and formatter.
- Elegance and Readability: Strive for elegant and Pythonic code that is easy to understand and maintain.
- Zen of Python: Keep the Zen of Python in mind when making design decisions.
- Avoid inheritance (prefer composition).
- Avoid methods (prefer non-class functions, or static).
- Name functions and variables in such a way that you don't need comments to explain the code.
- Python folder and filenames should all be snake_cased regardless of what they contain.
- Prefer importing entire modules instead of single functions: `from streamlit import mymodule` over `from streamlit.mymodule import internal_function`
- Prefer keyword arguments, use positional values only for required values that frame the API. Enhancing arguments should be keyword-only.
- Capitalize comments, use proper grammar and punctuation, and no cursing.
- Inside a module, anything that is declared at the root level MUST be prefixed with a _ if it's only used inside that module (anything private).
- Prioritize new features in Python 3.10+.
## Docstrings
- Use Numpydoc style.
- Docstrings are meant for users of a function, not developers who may edit the internals of that function in the future. If you want to talk to future developers, use comments.
- All modules that we expect users to interact with must have top-level docstrings. If a user is not meant to interact with a module, docstrings are optional.
## Package Structure
- `streamlit/`: The main Streamlit library package.
- `streamlit/elements`: Backend code of elements and widgets.
- `streamlit/runtime`: App runtime and execution logic.
- `streamlit/web`: Web server and CLI implementation
- `streamlit/commands`: `st` commands that don't add UI elements.
- `streamlit/components`: Backend-implementation of custom components.
- `streamlit/hello`: `streamlit hello` app implementation.
- `streamlit/navigation`: Multi-page app implementation.
- `streamlit/proto`: Generated protobuf definitions for client-server communication.
- `streamlit/testing`: AppTest v1 implementation.
- `streamlit/vendor`: Vendored dependencies.
- `streamlit/watcher`: File-watcher implementations.
- `streamlit/__init__.py`: Defines all commands in the `st` namespace.
- `setup.py`: Setup configuration of the Streamlit library.
- `tests`: Python unit tests (pytest).
## Typing
- Add typing annotations to every new function, method or class member.
- Use `typing_extensions` for back-porting newer typing features.
- Use future annotations via `from __future__ import annotations`.
## Relevant `make` commands
Run from the repo root:
- `make python-lint`: Lint and check formatting of Python files (ruff).
- `make python-tests`: Run all Python unit tests (pytest).
- `make python-types`: Run the Python type checker (mypy & ty).
- `make python-format`: Format Python files (ruff).
| 885
|
streamlit
|
streamlit/.cursor/rules/python_lib.mdc
|
---
description:
globs: lib/streamlit/**/*.py
alwaysApply: false
---
# Streamlit Lib Python Guide
Tips and guidelines specific to the development of the Streamlit Python library,
not applicable to scripts and e2e tests.
## Logging
If something needs to be logged, please use our logger - that returns a default
Python logger - with an appropriate logging level:
```python
from streamlit.logger import get_logger
_LOGGER: Final = get_logger(__name__)
```
## Unit Tests
We use the unit tests to cover internal behavior that can work without the web / backend
counterpart and the e2e tests to test the entire system. We aim for high unit test
coverage (90% or higher) of our Python code in `lib/streamlit`.
- Under `lib/tests/streamlit`, add a new test file
- Preferably in the mirrored directory structure as the non-test files.
- Naming: `my_example_test.py`
### Typing Tests
We also have typing tests in `lib/tests/streamlit/typing` for our public API to catch
typing errors in parameters or return types by using mypy and `assert_type`.
Check other typing tests in the `lib/tests/streamlit/typing` directory for inspiration.
| 314
|
streamlit
|
streamlit/.cursor/rules/python_tests.mdc
|
---
description:
globs: lib/tests/**/*.py
alwaysApply: false
---
# Python Unit Test Guide
We use the unit tests to cover internal behavior that can work without the web / backend counterpart.
We aim for high unit test coverage (90% or higher) of our Python code in `lib/streamlit`.
## Key Principles
- Prefer pytest or pytest plugins over unittest.
- For every new test function, please add a brief docstring comment (numpydoc style).
- New tests should be fully annotated with types.
- Skip tests (via `pytest.mark.skipif`) requiring CI secrets if the environment variables are not set.
- Parameterized Tests: Use `@parameterized.expand` whenever it is possible to combine overlapping tests with varying inputs.
## Running tests
- Run all with (execute from repo root):
```bash
make python-tests
```
- Run a specific test file with:
```bash
PYTHONPATH=lib pytest lib/tests/streamlit/my_example_test.py
```
- Run a specific test inside a test file with:
```bash
PYTHONPATH=lib pytest lib/tests/streamlit/my_example_test.py -k test_that_something_works
```
| 313
|
streamlit
|
streamlit/.cursor/rules/typescript.mdc
|
---
description:
globs: **/*.ts, **/*.tsx
alwaysApply: false
---
# TypeScript Development Guide
- TypeScript: v5
- Linter: eslint v9
- Formatter: prettier v3
- Framework: React v18
- Styling: @emotion/styled v11
- Build tool: vite v7
- Testing: vitest v3 & react testing library v16
- Package manager: yarn v4 with workspaces
## Key TypeScript Principles
- Prefer functional, declarative programming.
- Prefer iteration and modularization over duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading).
- Use the Receive an Object, Return an Object (RORO) pattern.
- Ensure functions have explicit return types.
- **Omit trivially inferred types**: Do not add type annotations when TypeScript can trivially infer them (e.g., `const count = 0` not `const count: number = 0`). Add explicit types only when they improve clarity or are required.
- **Prefer optional chaining**: Use optional chaining (`?.`) instead of `&&` chains for property access. This is enforced by the `@typescript-eslint/prefer-optional-chain` rule.
## Key Frontend Principles
- Leverage all of best practices of React 18.
- Follow the [Rules of React](https://react.dev/reference/rules): pure components and hooks, immutable props and state, and call hooks at the top level of React functions.
- Write performant frontend code.
- Ensure referential stability by leveraging React Hooks.
- **Updater functions must be pure**: `setState(prev => newState)` updaters must not mutate `prev` or have side effects—return a new object. See [useState](https://react.dev/reference/react/useState#setstate-parameters).
- Prefix event handlers with "handle" (e.g., handleClick, handleSubmit).
- Favor leveraging @emotion/styled instead of inline styles.
- Leverage object style notation in Emotion.
- All styled components begin with the word `Styled` to indicate it's a styled component.
- Utilize props in styled components to display elements that may have some interactivity.
- Avoid the need to target other components.
- When using BaseWeb, be sure to import our theme via `useEmotionTheme` and use those values in overrides.
- Use the following pattern for naming custom CSS classes and test IDs: `stComponentSubcomponent`, for example: `stTextInputIcon`.
- Avoid using pixel sizes for styling, always use rem, em, percentage, or other relative units.
## Static Data Structures
- Extract static lookup maps and constants to module-level scope outside functions/components
- Static data recreated on every call/render wastes memory and CPU
- Exception: Keep inside function only if data depends on parameters, props, or state
<good-example>
```tsx
// ✅ Module-level - created once
const ALIGNMENT_MAP: Record<Alignment, CSSProperties["textAlign"]> = {
[Alignment.LEFT]: "left",
[Alignment.CENTER]: "center",
// ...
} as const
function getAlignment(config: AlignmentConfig) {
return ALIGNMENT_MAP[config.alignment]
}
```
</good-example>
<bad-example>
```tsx
// ❌ Recreated every call
function getAlignment(config: AlignmentConfig) {
const alignmentMap = { /* same data */ }
return alignmentMap[config.alignment]
}
```
</bad-example>
## Yarn Workspaces
- Project Structure: Monorepo managed with Yarn Workspaces.
- Packages:
- `app` - Main application UI.
- `connection` - WebSocket handling
- `lib` - Shared UI components.
- `utils` - Shared TypeScript utilities.
- `protobuf` - Generated Protocol definitions.
- `typescript-config` - Configuration for TypeScript.
- `eslint-plugin-streamlit-custom` - ESLint plugin with custom rules.
- Package-specific scripts are executed within their respective directories.
## Relevant `make` commands
Run from the repo root:
- `make frontend-fast`: Build the frontend (vite).
- `make frontend-dev`: Start the frontend development server (hot-reload).
- `make frontend-lint`: Lint and check formatting of frontend files (eslint).
- `make frontend-types`: Run the TypeScript type checker (tsc).
- `make frontend-format`: Format frontend files (eslint).
- `make frontend-tests`: Run all frontend unit tests (vitest).
## TypeScript Test Guide
- Test Framework: Vitest
- UI Testing Library: React Testing Library (RTL)
### Key Principles
- Coverage: Implement both unit and integration tests (using RTL where applicable).
- Robustness: Test edge cases and error handling scenarios.
- Accessibility: Validate component accessibility compliance.
- Parameterized Tests: Use `it.each` for repeated tests with varying inputs.
- Framework Exclusivity: Only use Vitest syntax; do not use Jest.
### Running Tests
- Yarn test commands must be run from the `<GIT_ROOT>/frontend` directory.
- Run All Tests: `yarn test`
- Run Specific File: `yarn test lib/src/components/path/component.test.tsx`
- Run Specific Test: `yarn test -t "the test name" lib/src/components/path/component.test.tsx`
### React Testing Library best practices
Cheat sheet for queries from RTL:
| | No Match | 1 Match | 1+ Match | Await? |
| ---------- | -------- | ------- | -------- | ------ |
| getBy | throw | return | throw | No |
| findBy | throw | return | throw | Yes |
| queryBy | null | return | throw | No |
| getAllBy | throw | array | array | No |
| findAllBy | throw | array | array | Yes |
| queryAllBy | [] | array | array | No |
- Utilizing any query that throws if not found AND asserting using `toBeInTheDocument` is redundant and must be avoided. Prefer `toBeVisible` instead.
- User interactions should utilize the `userEvent` library.
- Tests should be written in a way that asserts user behavior, not implementation details.
#### Query Priority Order
Based on the Guiding Principles, your test should resemble how users interact with your code (component, page, etc.) as much as possible. With this in mind, we recommend this order of priority:
1. Queries Accessible to Everyone Queries that reflect the experience of visual/mouse users as well as those that use assistive technology.
- getByRole, getByLabelText, getByPlaceholderText, getByText, getByDisplayValue
2. Semantic Queries HTML5 and ARIA compliant selectors. Note that the user experience of interacting with these attributes varies greatly across browsers and assistive technology.
- getByAltText, getByTitle
3. Test IDs
- getByTestId - The user cannot see (or hear) these, so this is only recommended for cases where you can't match by role or text or it doesn't make sense (e.g. the text is dynamic).
## You Might Not Need an Effect
Authoritative rules for deciding when to use or remove `useEffect` in React components. Based on React docs: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect).
### Purpose
- Write React that is simpler, faster, and less error‑prone by avoiding unnecessary Effects.
- Prefer deriving values during render and handling actions in event handlers.
- Only use Effects to synchronize with external systems.
### Core Principles (enforce by default)
- Derive during render: If a value can be computed from props/state, compute it inline. Do NOT mirror it in state or set it in an Effect.
- Events, not Effects: Handle user interactions in event handlers. Do NOT move event-driven logic into Effects.
- Memoize expensive pure work: Use `useMemo` for heavy pure computations, not `useEffect` + state.
- One responsibility per Effect: Each Effect should sync exactly one external concern.
- Clean up or don’t ship: Any Effect that subscribes, starts timers, or allocates resources must return a cleanup.
- Stable refs over re-subscribes: Keep subscriptions stable; avoid recreating on every render.
### When an Effect IS appropriate
Use an Effect only to synchronize the component with an external system:
- Subscriptions: event listeners, WebSocket, ResizeObserver, etc. Ensure cleanup.
- Imperative APIs: integrating non-React widgets or DOM APIs.
- Network sync: Keep local UI in sync with remote data for given parameters (with race handling and cleanup).
- Scheduling/out-of-React side effects: analytics pings, imperative focus when tied to visibility.
If no external system is involved, you likely don’t need an Effect.
### Anti-patterns to reject (rewrite required)
- Setting derived state in an Effect (e.g., `setFullName(firstName + ' ' + lastName)`). Compute during render instead.
- Filtering/sorting data via Effect + state. Compute during render; use `useMemo` only if the computation is expensive.
- Using Effects to respond to user actions that can be handled in the event handler.
- Chains of Effects where each triggers the next via `setState`. Compute the final value directly during render or perform the action in the initiating handler.
- Missing cleanup for listeners, intervals, timeouts, blob URLs, or object URLs.
- Data fetching without race protection (stale response can overwrite newer data).
### Rewrite patterns (preferred code)
- Derived value during render:
```tsx
// ❌ Avoid
// const [fullName, setFullName] = useState("")
// useEffect(() => setFullName(`${firstName} ${lastName}`), [firstName, lastName])
// ✅ Do
const fullName = `${firstName} ${lastName}`
```
- Expensive pure computation:
```tsx
// ❌ Effect + state
// const [visibleTodos, setVisibleTodos] = useState<Todo[]>([])
// useEffect(() => setVisibleTodos(filterTodos(todos, filter)), [todos, filter])
// ✅ Render-time compute (useMemo only if slow)
const visibleTodos = useMemo(() => filterTodos(todos, filter), [todos, filter])
```
- Handle user action in the handler:
```tsx
// ❌ useEffect that watches flag and then performs action
// useEffect(() => { if (shouldBuy) buy() }, [shouldBuy])
// ✅ Directly do the work in response to the event
function handleBuyClick() {
void buy()
}
```
- Data fetching with race protection and cleanup:
```tsx
useEffect(() => {
const abort = new AbortController()
let ignore = false
fetch(makeUrl(query, page), { signal: abort.signal })
.then(r => r.json())
.then(data => {
if (!ignore) setResults(data)
})
.catch(err => {
if (!ignore && (err as any)?.name !== "AbortError") setError(err)
})
return () => {
ignore = true
abort.abort()
}
}, [query, page])
```
- Reset state without Effects:
```tsx
// ✅ Keyed reset when parent prop changes
;<Child key={userId} userId={userId} />
// ✅ Set initial controlled values from props during render
const initialTab = props.defaultTab ?? "overview"
```
### Effect checklist (must pass all)
1. External sync: Does this Effect synchronize with an external system? If no, remove it.
2. Single responsibility: Exactly one external concern in this Effect.
3. Complete deps: Dependency array is complete and correct; avoid stale closures.
4. Cleanup: All listeners, timers, object URLs, and subscriptions are cleaned in the return function.
5. Race safety: For network requests, ignore/cancel stale responses (AbortController or an `ignore` flag).
6. Referential stability: Use `useCallback`/`useMemo` to prevent unnecessary effect re-runs caused by unstable references.
7. Error handling: Async paths have error handling; no silent failures.
### Decision guide
- Can it be computed from existing state/props? Compute during render.
- Is the logic triggered by a user event? Put it in the event handler.
- Is it an expensive pure calculation? Use `useMemo` (not Effect) to cache.
- Are you integrating with something outside React? Use an Effect with cleanup.
- Are you fetching data tied to inputs/visibility? Use an Effect with race handling and cleanup.
### Review heuristics (quick scans)
- Search for `useEffect` followed by immediate `setState` of values derivable from render inputs.
- Effects that only read props/state and don’t touch external systems are candidates for removal.
- Multiple Effects updating each other’s state in a chain indicate a missing render-time computation or misplaced event logic.
- Effects creating event listeners/timers without `return` cleanup are bugs.
### Performance notes
- Prefer render-time computation; add `useMemo` only for provably expensive pure work.
- Avoid creating new objects/arrays inline in JSX props each render; memoize when it affects memoized children.
- Keep dependency arrays minimal but complete. Split Effects if different concerns require different deps.
### Testing guidance (see [TypeScript Test Guide](#typescript-test-guide))
- Unit test render-time derivations directly (no Effects involved).
- For Effects that fetch or subscribe, test cleanup and race handling (use fake timers/abort signals).
- RTL: assert behavior and results, not internal hook usage.
### References
- React docs: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
| 3,579
|
streamlit
|
streamlit/.cursor/worktrees.json
|
{
"setup-worktree": [
"cd \"$(git rev-parse --show-toplevel)\"; [ -d .venv ] || uv venv; VIRTUAL_ENV=.venv PATH=\".venv/bin:.venv/Scripts:$PATH\" make all-dev frontend"
]
}
| 87
|
streamlit
|
streamlit/.devcontainer/Dockerfile
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 mcr.microsoft.com/devcontainers/python:3.12
ENV PYTHONUNBUFFERED=1
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0
# Install system dependencies
RUN apt-get update && apt-get install -y \
build-essential \
curl \
git \
rsync \
unzip \
protobuf-compiler \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js
RUN curl -sL https://deb.nodesource.com/setup_22.x | bash - \
&& apt-get install -y nodejs
# Enable corepack
RUN corepack enable
# Update pip
RUN pip install --upgrade pip
| 374
|
streamlit
|
streamlit/.devcontainer/devcontainer.json
|
{
"name": "streamlit-dev",
"build": {
"dockerfile": "Dockerfile"
},
"forwardPorts": [3000],
"portsAttributes": {
"3000": {
"label": "Dev Server",
"onAutoForward": "notify"
}
},
"customizations": {
"vscode": {
"extensions": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"ms-python.mypy-type-checker",
"ms-python.python",
"ms-python.debugpy",
"ms-python.vscode-pylance",
"charliermarsh.ruff",
"EditorConfig.EditorConfig",
"vitest.explorer",
"tamasfe.even-better-toml"
],
"settings": {
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit",
"source.organizeImports.ruff": "explicit"
},
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": true
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
},
"[yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[yml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[toml]": {
"editor.defaultFormatter": "tamasfe.even-better-toml",
"editor.formatOnSave": true
},
"files.trimTrailingWhitespace": true,
"files.trimFinalNewlines": true,
"files.insertFinalNewline": true,
"search.exclude": {
"lib/build/**": true
},
"makefile.configureOnOpen": false,
"eslint.workingDirectories": [
{
"mode": "auto"
}
],
"eslint.lintTask.enable": true,
"editor.codeActionsOnSave": {
"source.fixAll": "always"
},
"vitest.maximumConfigs": 5,
"mypy-type-checker.importStrategy": "fromEnvironment",
"mypy-type-checker.preferDaemon": false,
"mypy-type-checker.args": ["--config-file=mypy.ini"],
"ruff.nativeServer": true,
"ruff.organizeImports": true,
"ruff.fixAll": true,
"python.analysis.exclude": ["lib/build"],
"python.analysis.include": [
"lib/**/*",
"scripts/**/*",
"e2e_playwright/**/*"
],
"python.analysis.extraPaths": ["./lib"],
"python.analysis.typeCheckingMode": "off",
"python.terminal.activateEnvInCurrentTerminal": true,
"python.testing.pytestEnabled": true,
"python.testing.autoTestDiscoverOnSaveEnabled": true,
"cursorpyright.analysis.exclude": ["lib/build"],
"cursorpyright.analysis.include": [
"lib/**/*",
"scripts/**/*",
"e2e_playwright/**/*"
],
"cursorpyright.analysis.extraPaths": ["./lib"],
"cursorpyright.analysis.typeCheckingMode": "off",
"cursorpyright.analysis.useTypingExtensions": true,
"cursorpyright.shouldImportPylanceSettings": "always",
"cursorpyright.analysis.logLevel": "Information",
"terminal.integrated.profiles.linux": {
"frontend-dev": {
"path": "bash",
"args": ["-c", "make frontend-dev"]
}
},
"typescript.tsdk": "frontend/node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"git.branchProtection": ["develop"]
}
}
},
"updateContentCommand": "make all-dev",
"postStartCommand": "make frontend-dev"
}
| 2,229
|
streamlit
|
streamlit/.editorconfig
|
# https://editorconfig.org/
root = true
[*]
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
charset = utf-8
max_line_length = 79
[*.py]
indent_size = 4
max_line_length = 88
# The JSON files contain newlines inconsistently
[*.json]
insert_final_newline = ignore
[**/node_modules/**]
indent_style = ignore
indent_size = ignore
[**.min.js]
indent_style = ignore
insert_final_newline = ignore
[Makefile]
indent_style = tab
| 188
|
streamlit
|
streamlit/.nvmrc
|
v24
| 3
|
streamlit
|
streamlit/.pre-commit-config.yaml
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# Pre-commit configuration file,
# when Streamlit's pre-commit detects that one of the linters has failed,
# it automatically lints the files and does not allow the commit to pass.
# Please review the changes after lint has failed and commit them again,
# the second commit should pass,
# because the files were linted after trying to do the first commit.
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# We fix ruff to a version to be in sync with the dev-requirements:
rev: v0.14.7
hooks:
# Run the linter.
- id: ruff
args: [--fix]
files: \.py$|\.pyi$
# Run the formatter.
- id: ruff-format
files: \.py$|\.pyi$
- repo: local
hooks:
# Script ./scripts/run_in_subdirectory.py was used to work around a
# known problem with hooks in subdirectories when pass_filenames option
# is set to true
# See: https://github.com/pre-commit/pre-commit/issues/1417
- id: prettier-app
name: Prettier App
# NOTE: This hook currently does not work on Windows due to "yarn" not being an executable and win32api.CreateProcess
# turning `subprocess.run(["yarn", "prettier", "--write"])` into a call to `yarn.exe prettier --write` which does not exist
entry: ./scripts/run_in_subdirectory.py frontend/app yarn run format
files: ^frontend/app/.*\.(js|jsx|ts|tsx)$
exclude: /vendor/
language: node
pass_filenames: true
- id: prettier-lib
name: Prettier Lib
# NOTE: This hook currently does not work on Windows due to "yarn" not being an executable and win32api.CreateProcess
# turning `subprocess.run(["yarn", "prettier", "--write"])` into a call to `yarn.exe prettier --write` which does not exist
entry: ./scripts/run_in_subdirectory.py frontend/lib yarn run format
files: ^frontend/lib/.*\.(js|jsx|ts|tsx)$
exclude: /vendor/
language: node
pass_filenames: true
- id: prettier-connection
name: Prettier Connection
# NOTE: This hook currently does not work on Windows due to "yarn" not being an executable and win32api.CreateProcess
# turning `subprocess.run(["yarn", "prettier", "--write"])` into a call to `yarn.exe prettier --write` which does not exist
entry: ./scripts/run_in_subdirectory.py frontend/connection yarn run format
files: ^frontend/connection/.*\.(js|jsx|ts|tsx)$
exclude: /vendor/
language: node
pass_filenames: true
- id: prettier-utils
name: Prettier Utils
# NOTE: This hook currently does not work on Windows due to "yarn" not being an executable and win32api.CreateProcess
# turning `subprocess.run(["yarn", "prettier", "--write"])` into a call to `yarn.exe prettier --write` which does not exist
entry: ./scripts/run_in_subdirectory.py frontend/utils yarn run format
files: ^frontend/utils/.*\.(js|jsx|ts|tsx)$
exclude: /vendor/
language: node
pass_filenames: true
- id: prettier-yaml
name: Prettier-yaml
# NOTE: This hook currently does not work on Windows due to "yarn" not being an executable and win32api.CreateProcess
# turning `subprocess.run(["yarn", "prettier", "--write"])` into a call to `yarn.exe prettier --write` which does not exist
# We perform this in the app directory because prettier is installed there. TODO: Break this out to a new package
entry: ./scripts/run_in_subdirectory.py frontend/app yarn prettier "../../.github/**/*.{yml,yaml}" --write
files: ^.github/.*\.(yml|yaml)$
language: node
pass_filenames: false
- id: prettier-vscode-devcontainer-json
name: Prettier VSCode/devcontainer JSON
# NOTE: This hook currently does not work on Windows due to "yarn" not being an executable and win32api.CreateProcess
# turning `subprocess.run(["yarn", "prettier", "--write"])` into a call to `yarn.exe prettier --write` which does not exist
# We perform this in the app directory because prettier is installed there. TODO: Break this out to a new package
entry: ./scripts/run_in_subdirectory.py frontend/app yarn prettier "../../.vscode/*.json" "../../.devcontainer/*.json" --write --config ../.prettierrc
files: ^(.vscode/.*\.json|\.devcontainer/.*\.json)$
language: node
pass_filenames: false
- id: license-headers
name: Checks license headers
entry: ./scripts/check_license_headers.py
language: system
always_run: true
pass_filenames: false
- id: generate-agent-rules
name: Check generated agent rules
entry: ./scripts/generate_agent_rules.py
language: system
pass_filenames: false
files: |
(?x)
(^|.*/)AGENTS\.md$
|^scripts/generate_agent_rules\.py$
|^Makefile$
- id: vscode-devcontainer-sync
name: Check VSCode/devcontainer sync
entry: ./scripts/sync_vscode_devcontainer.py --check
language: system
files: ^(.vscode/(settings|extensions)\.json|\.devcontainer/devcontainer\.json)$
pass_filenames: false
- id: yarn-dedupe
name: Check frontend yarn.lock dedupe
entry: ./scripts/check_yarn_dedupe.sh frontend
language: system
pass_filenames: false
files: ^frontend/yarn\.lock$
- repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.5.5
hooks:
- id: insert-license
name: Add license for all (S)CSS/JS(X)/TS(X) files
files: \.(s?css|jsx?|tsx?)$
args:
- --comment-style
- "/**| *| */"
- --license-filepath
- scripts/assets/license-template.txt
- --fuzzy-match-generates-todo
exclude: |
(?x)
/vendor/
|^vendor/
|^component-lib/declarations/apache-arrow
|^frontend/app/src/assets/css/variables\.scss
|^lib/tests/streamlit/elements/test_html\.js
|^lib/tests/streamlit/elements/test_html\.css
|^e2e_playwright/test_assets/
- id: insert-license
name: Add license for all Proto files
files: \.proto$
args:
- --comment-style
- "/**!| *| */"
- --license-filepath
- scripts/assets/license-template.txt
- --fuzzy-match-generates-todo
exclude: |
(?x)
/vendor/
|^vendor/
|^component-lib/declarations/apache-arrow
|^proto/streamlit/proto/openmetrics_data_model\.proto
- id: insert-license
name: Add license for all shell files
files: \.sh$
args:
- --comment-style
- "|#|"
- --license-filepath
- scripts/assets/license-template.txt
- --fuzzy-match-generates-todo
exclude: |
(?x)
/vendor/
|^vendor/
|^component-lib/declarations/apache-arrow
- id: insert-license
name: Add license for all Python files
files: \.py$|\.pyi$
args:
- --comment-style
- "|#|"
- --license-filepath
- scripts/assets/license-template.txt
- --fuzzy-match-generates-todo
exclude: |
(?x)
/vendor/
|^vendor/
|^component-lib/declarations/apache-arrow
- id: insert-license
name: Add license for all HTML files
files: \.html$
args:
- --comment-style
- "<!--||-->"
- --license-filepath
- scripts/assets/license-template.txt
- --fuzzy-match-generates-todo
exclude: |
(?x)
/vendor/
|^vendor/
|^component-lib/declarations/apache-arrow
- repo: https://gitlab.com/bmares/check-json5
rev: v1.0.0
hooks:
# Check JSON files that are allowed to have comments
- id: check-json5
# Note that this should be the same as the check-json hook's exclude
# property
files: |
(?x)
^\.vscode/.*\.json$
|tsconfig.*\.json$
|.*tsconfig\.json$
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
exclude: |
(?x)
^frontend/app/src/assets/
|^NOTICES$
|^proto/streamlit/proto/openmetrics_data_model.proto$
|\.snap$
- id: check-added-large-files
- id: check-json
# Note that this should be the same as the check-json5 hook's files
# property
exclude: |
(?x)
^\.vscode/.*\.json$
|tsconfig.*\.json$
|.*tsconfig\.json$
- id: check-toml
- id: check-yaml
exclude: lib/conda-recipe/meta.yaml
- id: check-symlinks
- id: check-case-conflict
- id: check-merge-conflict
- id: fix-byte-order-marker
- id: end-of-file-fixer
exclude: |
(?x)
/vendor/
|^NOTICES$
|^e2e_playwright/test_assets/
|^LICENSE$
- id: mixed-line-ending
args: [--fix=lf]
exclude: |
(?x)
^NOTICES$
| 4,405
|
streamlit
|
streamlit/.ruff.toml
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# In addition to the standard set of exclusions, omit all tests:
extend-exclude = [
# Autogenerated files:
"lib/streamlit/proto",
"lib/streamlit/emojis.py",
"lib/streamlit/material_icon_names.py",
# File with an expected compilation error:
"e2e_playwright/compilation_error_dialog.py",
# Ignore frontend directory:
"frontend/**",
]
target-version = 'py310'
line-length = 88
[format]
docstring-code-format = true
docstring-code-line-length = "dynamic"
line-ending = "lf"
[lint]
# We activate all rules and only ignore the rules that we don't want to enforce
# or that are not relevant for our codebase.
select = ["ALL"]
ignore = [
# Rules planned to be supported in the future:
"EM101", # Checks for the use of string literals in exception constructors.
"EM102", # Checks for the use of f-strings in exception constructors.
"TRY003", # Checks for exception messages that are not defined in the exception class itself.
# Ignored rule sets:
"DTZ", # Checks for usage of unsafe naive datetime class.
"PTH", # Enforces usage of pathlib.
"C90", # Checks for McCabe complexity.
"FBT", # Forbids boolean positional arguments.
"SLF", # Checks unexpected for private member access.
"BLE", # Checks for blind except statements.
"CPY", # Checks for copyright statement.
"DOC", # Checks for correct docstring format.
# Ignored rules:
"B904", # Checks for raise statements in exception handlers that lack a from clause.
"PYI041", # Checks for parameter annotations that contain redundant unions between builtin numeric types (e.g., int | float).
"PYI051", # Checks for redundant unions between a Literal and a builtin supertype of that Literal.
"PD009", # Checks for usage of pd.DataFrame.iat.
"PIE790", # Checks for unnecessary pass statements.
"TD003", # Checks for missing issue link in TODO comment.
"TD002", # Checks for missing author in TODO comment.
"D100", # Checks for missing docstring in public module.
"D101", # Checks for missing docstring in public class.
"D102", # Checks for missing docstring in public method.
"D103", # Checks for missing docstring in public function.
"D104", # Checks for missing docstring in public package.
"D105", # Checks for missing docstring in magic method.
"D106", # Checks for missing docstring in public nested class.
"D107", # Checks for missing docstring in __init__.
"D205", # Checks for missing blank line after docstring summary.
"D401", # Checks for docstring to start with imperative mood.
"D202", # Checks for no-blank line after docstring.
"FIX002", # Checks todo comments (which we want to allow).
"PGH003", # Checks for blanket type ignore.
"PLR2004", # Checks for numerical values that could be put into a constant.
"PLR0904", # Checks for classes with too many public methods.
"PLR0911", # Checks for functions with too many return statements.
"PLR0912", # Checks for functions with too many branches.
"PLR0913", # Checks for functions with too many arguments.
"PLR0914", # Checks for functions with too many local variables.
"PLR0915", # Checks for functions with too many statements.
"PLR0916", # Checks for too many boolean expressions in if statements.
"A002", # Checks if function argument shadows a Python builtin.
"TRY300", # Checks for return statements in try blocks.
"ANN401", # Checks that `any` is not used as an annotation.
"SIM105", # Enforces use of contextlib.suppress.
"SIM108", # Enforces ternary operators instead of if-else.
"SIM115", # Enforces context manager for opening files.
"SIM117", # Enforces single with statement with multiple contexts.
"SIM905", # Enforces list instead of st.split.
"COM812", # Checks for absence of trailing commas. Not recommended with formatter.
"COM819", # Checks for presence of prohibited trailing commas. Not recommended with formatter.
"RSE102", # Checks for unnecessary parentheses on raised exceptions.
"RET504", # Checks for assignments that immediately precede a return of the assigned variable (too opinionated).
"PT012", # Checks for pytest.raises context managers with multiple statements.
"PT019", # Checks for tests that should use @pytest.mark.usefixtures (incompatible with unittest.patch)
"PLC0415", # Enforces imports to be at the top-level of the file.
]
exclude = [
# pympler is a vendored dependency that doesn't conform to our linting rules:
"lib/streamlit/vendor/**",
]
extend-safe-fixes = ["TC002", "TC003"]
[lint.per-file-ignores]
# Only add ignores for entire folders here. To ignore rules in individual
# files, use the noqa ignore comment on top of the given file.
"e2e_playwright/**" = [
"T20",
"B018",
"PD",
"PERF",
"N999",
"S",
"TRY",
"NPY002",
]
"lib/tests/**" = [
"PD",
"D",
"INP",
"PERF",
"N",
"ARG",
"S",
"TRY",
"ANN",
"NPY002",
]
"scripts/**" = ["T20", "INP", "PERF", "S", "TRY002"]
[lint.flake8-tidy-imports]
# Disallow all relative imports.
ban-relative-imports = "all"
[lint.isort]
known-first-party = ["streamlit", "shared", "tests", "e2e_playwright"]
[lint.pydocstyle]
convention = "numpy"
[lint.pycodestyle]
# Allow lines (e.g. comments) up to 120 characters instead of 88,
# which works well with Github.
max-line-length = 120
[lint.flake8-comprehensions]
# Allow dict calls that make use of keyword arguments (e.g., dict(a=1, b=2)).
allow-dict-calls-with-keyword-arguments = true
[lint.flake8-unused-arguments]
# Ignore unused variadic argument, like *args and **kwargs.
ignore-variadic-names = true
[lint.flake8-annotations]
# Allow missing return annotation on functions that return None:
suppress-none-returning = true
| 1,969
|
streamlit
|
streamlit/.vscode/extensions.json
|
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"ms-python.mypy-type-checker",
"ms-python.python",
"ms-python.debugpy",
"ms-python.vscode-pylance",
"charliermarsh.ruff",
"EditorConfig.EditorConfig",
"vitest.explorer",
"tamasfe.even-better-toml",
"anysphere.cursorpyright"
]
}
| 172
|
streamlit
|
streamlit/.vscode/launch.json
|
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug Streamlit App",
"type": "debugpy",
"request": "launch",
"module": "streamlit",
"args": ["run", "${file}"]
// allows to set breakpoints in installed packages, such as the Streamlit lib itself or custom component code etc.
// "justMyCode": false,
// allows to use a different installed version of streamlit in another venv folder, e.g.
// "program": "~/Projects/streamlit/lib/venv/bin/pytest"
}
]
}
| 254
|
streamlit
|
streamlit/CLAUDE.md
|
@./AGENTS.md
| 7
|
streamlit
|
streamlit/CODE_OF_CONDUCT.md
|
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at hello@streamlit.io. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
| 694
|
streamlit
|
streamlit/CONTRIBUTING.md
|
Thanks for your interest in helping improve Streamlit! 🎉
**If you are looking for Streamlit's documentation, go here instead: <https://docs.streamlit.io>**
This wiki is for people who want to contribute code to Streamlit. There are also other ways to contribute, such as [reporting bugs](https://github.com/streamlit/streamlit/issues/new?template=bug_report.yml), creating [feature requests](https://github.com/streamlit/streamlit/issues/new?template=feature_request.yml), helping other users [in our forums](https://discuss.streamlit.io), Stack Overflow, etc., or just being an awesome member of the community!
## Before contributing
**If your contribution is more than a few lines of code, then prior to starting to code on it please post in the issue saying you want to volunteer, and then wait for a positive response.** And if there is no issue for it yet, create it first.
This helps make sure:
1. Two people aren't working on the same thing
2. This is something Streamlit's maintainers believe should be implemented/fixed
3. Any API, UI, or deeper architectural changes that need to be implemented have been fully thought through by Streamlit's maintainers
4. Your time is well spent!
> [!TIP]
> To be clear: if you open a PR that adds a new feature (and isn't just a bug fix or similar) *without* prior support from the Streamlit team, the chances of getting it merged are *extremely low*. Adding a new feature comes with a lot of baggage, such as thinking through the exact API, making sure it fulfills our standards, and maintaining it in the future – even if it's just a small parameter.
## Style Guide
Check out [Streamlit's style guide](./wiki/code-style-guide.md). We use [Prettier](https://prettier.io), [Ruff](https://github.com/astral-sh/ruff) and [ESLint](https://eslint.org/) to format and lint code, but some things go beyond what auto-formatters and linters can do. So please take a look!
## How to build Streamlit
### 1. Set up your base environment
#### MacOS
```bash
# Some Apple dev tools (developer.apple.com/downloads)
$ xcode-select --install
# Install Homebrew
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install the Protobuf compiler
$ brew install protobuf
```
**Installing Node JS and yarn**
We recommend that you [manage your nodejs installation with nvm](https://github.com/nvm-sh/nvm#install--update-script).
After following the instructions linked above to install `nvm`, use the following command to install the latest supported node version
```bash
# Install node
nvm install node
```
**Note:** Node has added Corepack which is a manager of package managers 🥳. It supports yarn! You can enable it by running the following:
```bash
corepack enable
```
You may need to `brew install corepack` depending on how you installed node.
#### Ubuntu
```bash
# Install some essentials
$ sudo apt-get update
$ sudo apt-get install -y sudo make build-essential curl git rsync unzip protobuf-compiler
# Set frontend dependencies:
$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
$ source ~/.bashrc
$ nvm install node
$ corepack enable
# Install uv for Python
$ curl -LsSf https://astral.sh/uv/install.sh | sh
# Install virtual environment in lib:
$ cd lib/
$ uv venv --python 3.12
$ source .venv/bin/activate
```
#### Windows
Streamlit's development setup is pretty Mac- and Linux-centric. If you're doing Streamlit development on Windows, we suggest using our [devcontainer](./.devcontainer) via Github Codespaces or locally via VS Code. Alternatively, you can also spin up a Linux VM (e.g. via [VirtualBox](https://www.virtualbox.org/), which is free); or your own Linux Docker image; or using Microsoft's WSL ("Windows Subsystem for Linux").
### 2. Grab the code
*(You probably already know how to do this, but just in case...)*
First fork [the repo](https://github.com/streamlit/streamlit) via the UI on Github and then do the following:
```bash
git clone https://github.com/${YOUR_NAME}/streamlit.git
cd streamlit
git remote add remote https://github.com/streamlit/streamlit.git
git checkout develop
git submodule update --init
git checkout -b ${BRANCH_NAME}
```
### 3. Create a new Python environment
Create a virtual environment for Streamlit using your favorite tool (`virtualenv`, `pipenv`, etc) and activate it. Here's how we do it with [`venv`](https://docs.python.org/3/library/venv.html):
```bash
cd lib
python -m venv venv
```
Note that, with `venv` this process should be done from any directory, but it is recommended to do it from the `lib/` directory to keep all python files in one directory.
```bash
source ./venv/bin/activate
```
## How to develop Streamlit
The basic developer workflow is that you run a React development server on port 3000 in one terminal and run Streamlit CLI commands in another terminal.
### 1. One-time setup
```bash
make all-dev
```
### 2. Build the frontend
```bash
make frontend
```
### 3. Start the dev server (hot-reloading)
The easiest way to start the dev server from the terminal, is to run:
```bash
make frontend-dev
```
> [!Note]
> This server listens on port `3000` rather than `8501` (i.e. Streamlit's production port). Normally you don't have to worry about this, but it may matter when you're developing certain features. The server is automatically updating to the changes you apply in the frontend code (hot-reloading).
### 4. Run Streamlit
Open another terminal, start your Python environment and run Streamlit.
If you're using `venv`, that's:
```bash
$ cd lib
$ source ./venv/bin/activate
$ cd ..
# Now run any Streamlit command you want, such as:
$ streamlit hello
```
### 5. What to do when you modify some code
#### When you modify JS, or CSS code
Since we use that awesome dev server above, when you change any JS/CSS code everything should automatically *just work* without the need to restart any of the servers.
#### When you modify Python code
When you modify Python code, you should kill the old Streamlit server, if any (<key>ctrl-c</key> on the terminal) and then restart it.
#### When you update protobufs
If you ever modify our protobufs, you'll need to run the command below to compile
the protos into libraries that can be used in Python and JS:
```bash
make protobuf
```
#### When Javascript or Python dependencies change
```bash
make init
```
> [!IMPORTANT]
> If your change updates `frontend/yarn.lock` (for example, after adding or upgrading dependencies), run `cd frontend && yarn dedupe` before committing. Our `scripts/check_yarn_dedupe.sh` hook enforces this locally (via pre-commit) and in CI, so handling it upfront keeps your PR green.
### 6. Running tests
You should always write unit tests and end-to-end tests! This is true for new features, but also for bugs; this way when you fix a bug you can be sure it will not show up again. So bug-fixing is actually a great way to increase our test coverage where it actually matters.
#### Python unit tests
- Run all with:
```bash
make python-tests
```
- Run a specific test file with:
```bash
PYTHONPATH=lib pytest lib/tests/streamlit/the_test_name.py
```
- Run a specific test inside a test file with:
```bash
PYTHONPATH=lib pytest lib/tests/streamlit/the_test_name.py -k test_that_something_works
```
- Some tests require you to set up credentials to connect to Snowflake and install [the `snowflake-snowpark-python` package](https://pypi.org/project/snowflake-snowpark-python/). Information on how the Snowflake environment is set up is in our [test utils](./lib/tests/testutil.py) including environment variables to be set. They are skipped by default when running tests. To enable them and disable all others, pass the `--require-integration` flag to `pytest`.
```bash
PYTHONPATH=lib pytest --require-integration
```
#### JS unit tests
- Run all with:
```bash
make frontend-tests
```
- Run specific tests:
```bash
cd frontend
yarn workspace @streamlit/lib test src/path/to/test_file.test.ts
```
NOTE: Making changes to a react component may cause unit snapshot tests (which are designed to catch unintended changes to jsx/tsx components) to fail. Once you've double-checked that all of the changes in the failing snapshot test are expected, you can follow the prompts that appear after running `make frontend-tests` to update the snapshots, check them into source control, and include them in your PR.
#### End-to-end tests
You can find information about our e2e testing setup [here](./wiki/running-e2e-tests.md).
### 7. Formatting, linting, and type-checking
We've set up various formatting, linting, and type-checking rules that our Continuous Integration checks to maintain code quality and consistency. Before merging a Pull Request, all formatting and linting rules must be satisfied and passed successfully.
### Python
For Python, we use [ruff](https://github.com/astral-sh/ruff) for formatting & linting and [mypy](https://github.com/python/mypy) for type-checking.
#### Formatting
To format all Python code & sort the imports, run the following command:
```bash
make python-format
```
Alternatively, you can use the `ruff format` command directly.
#### Linting
To run the linter, use the command below:
```bash
make python-lint
```
Alternatively, you can use the `ruff check` command directly.
#### Type-checking
For type-checking, run:
```bash
make python-types
```
### Javascript / Typescript
For Javascript/Typescript, we utilize Prettier and ESLint.
#### Formatting
To format your code, run this command:
```bash
make frontend-format
```
#### Linting
To initiate the linting process, use this command:
```bash
make frontend-lint
```
#### Type-checking
For type-checking, run:
```bash
make frontend-types
```
### VS-Code / Cursor Setup
For development in VS Code, we recommend installing the extensions listed in [`.vscode/extensions.json`](./.vscode/extensions.json) and for an optimized configuration you can use the VS-Code settings from [`.devcontainer/devcontainer.json`](./.devcontainer/devcontainer.json).
### Pre-commit hooks
When Streamlit's pre-commit detects that one of the linters has failed,
it automatically lints the files and does not allow the commit to pass.
Please review the changes after lint has failed and commit them again,
the second commit should pass,
because the files were linted after trying to do the first commit.
But you can run pre-commit hooks manually as needed.
- Run all checks on your staged files by using:
```shell
pre-commit run
```
- Run all checks on all files by using:
```shell
pre-commit run --all-files
```
## Troubleshooting
#### Test `test_streamlit_version` fails
```python
def test_streamlit_version(self):
"""Test streamlit.__version__."""
self.assertEqual(__version__, get_version())
AssertionError: '1.11.0' != '1.11.1'
- 1.11.0
? ^
+ 1.11.1
? ^
```
To fix this make sure you have setup your Python's venv environments correctly, upgrade your dependencies or recreate your environment and repeat setup.
You might have double environments which mismatch for example by accident you could have created venv Python environment inside `streamlit` repository and second one inside `streamlit/lib`. Remove them.
#### `protoc` command fails because of version mismatch
If the `protoc` command fails and there is a version mismatch reported, try to install the correct version.
- Go to [Protobuf releases](https://github.com/protocolbuffers/protobuf/releases)
- Choose the [Protobuf tag](https://github.com/protocolbuffers/protobuf/tags) which matches Python's environment Protobuf version, for example [3.20.0](https://github.com/protocolbuffers/protobuf/releases/tag/v3.20.0). Call `pip show protobuf` or equivalent to find this out.
- Download zip containing protoc for your system, example: [protoc-3.20.0-osx-x86_64.zip](https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protoc-3.20.0-osx-x86_64.zip)
<details>
<summary>Example for macOS</summary>
```bash
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protoc-3.20.0-osx-x86_64.zip
sudo unzip -o protoc-3.20.0-osx-x86_64.zip -d /usr/local bin/protoc
sudo unzip -o protoc-3.20.0-osx-x86_64.zip -d /usr/local 'include/*'
# Print out your System's Protoc version
protoc --version
```
</details>
<details>
<summary>Example for Linux (ARM)</summary>
```bash
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protoc-3.20.0-linux-aarch_64.zip
sudo unzip -o protoc-3.20.0-linux-aarch_64.zip -d /usr/local bin/protoc
sudo unzip -o protoc-3.20.0-linux-aarch_64.zip -d /usr/local 'include/*'
# (optional) remove old version
rm /usr/bin/protoc
ln -s /usr/local/bin/protoc /usr/bin/protoc
# Print out your System's Protoc version
protoc --version
```
</details>
#### Installing conda and conda-build
If you want to build Streamlit as a conda package on your local machine (needing to do this should be rare), you'll need to install a few extra dependencies so that the `make conda-package` target works.
1. First, install `conda` using your favorite package manager or by following [these instructions](https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html). Both `anaconda` and `miniconda` will work.
2. Then, run `conda install conda-build`.
## Introducing dependencies
We aim to only introduce dependencies in this project that have reasonable restrictions and comply with various laws.

| 4,042
|
streamlit
|
streamlit/LICENSE
|
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
| 3,168
|
streamlit
|
streamlit/Makefile
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
# Make uses /bin/sh by default, but we are using some bash features. On Ubuntu
# /bin/sh is POSIX compliant, ie it's not bash. So let's be explicit:
SHELL=/bin/bash
INSTALL_DEV_REQS ?= true
INSTALL_TEST_REQS ?= true
INSTALL_PLAYWRIGHT ?= true
# Flags:
# - INSTALL_DEV_REQS: install dev requirements (default: true)
# - INSTALL_TEST_REQS: install test requirements (default: true)
# - INSTALL_PLAYWRIGHT: install Playwright browsers during python-init (default: true)
# CI uses a dedicated action to install browsers and typically sets this to false.
# Local dev can opt out when not needed: `INSTALL_PLAYWRIGHT=false make init`
PYTHON_VERSION := $(shell python --version | cut -d " " -f 2 | cut -d "." -f 1-2)
MIN_PROTOC_VERSION = 3.20
# Check if Python is installed and can be executed, otherwise show an error message in red (but continue)
ifeq ($(PYTHON_VERSION),)
error_message="Error: Python version is not detected. Please ensure Python is installed and accessible in your PATH."
error_message_red_colored=$(shell echo -e "\033[0;31m ${error_message} \033[0m")
$(warning ${error_message_red_colored})
endif
.PHONY: help
# Show all available make commands.
help:
@# Magic line used to create self-documenting makefiles.
@# Note that this means the documenting comment just before the command (but after the .PHONY) must be all one line, and should begin with a capital letter and end with a period.
@# See https://stackoverflow.com/a/35730928
@awk '/^#/{c=substr($$0,3);next}c&&/^[[:alpha:]][[:alnum:]_-]+:/{print substr($$1,1,index($$1,":")-1) ";" c}1{c=0}' Makefile | column -s';' -t
.PHONY: all
# Install all dependencies, build frontend, and install editable Streamlit.
all: init frontend
.PHONY: all-dev
# Install all dependencies and editable Streamlit, but do not build the frontend.
all-dev: init
pre-commit install
@echo ""
@echo " The frontend has *not* been rebuilt."
@echo " If you need to make a wheel file, run:"
@echo ""
@echo " make frontend"
@echo ""
.PHONY: init
# Install all dependencies and build protobufs.
init: python-init frontend-init protobuf
.PHONY: clean
# Remove all generated files.
clean:
cd lib; rm -rf build dist .eggs *.egg-info
rm -rf lib/conda-recipe/dist
find . -name '*.pyc' -type f -delete || true
find . -name __pycache__ -type d -delete || true
find . -name .pytest_cache -exec rm -rfv {} \; || true
find . -name '.benchmarks' -type d -exec rm -rfv {} \; || true
rm -rf .mypy_cache
rm -rf .ruff_cache
rm -f lib/streamlit/proto/*_pb2.py*
rm -rf lib/streamlit/static
rm -f lib/Pipfile.lock
rm -rf frontend/app/build
rm -rf frontend/node_modules
rm -rf frontend/app/performance/lighthouse/reports
rm -rf frontend/app/node_modules
rm -rf frontend/lib/node_modules
rm -rf frontend/connection/node_modules
rm -rf frontend/test_results
rm -f frontend/protobuf/proto.js
rm -f frontend/protobuf/proto.d.ts
rm -rf frontend/public/reports
rm -rf frontend/lib/dist
rm -rf frontend/connection/dist
rm -rf frontend/component-v2-lib/dist
rm -rf ~/.cache/pre-commit
rm -rf e2e_playwright/test-results
rm -rf e2e_playwright/performance-results
find . -name .streamlit -not \( -path './e2e_playwright/.streamlit' -o -path './e2e_playwright/config/.streamlit' \) -type d -exec rm -rfv {} \; || true
cd lib; rm -rf .coverage .coverage\.*
.PHONY: protobuf
# Recompile Protobufs for Python and the frontend.
protobuf:
# Ensure protoc is installed and is >= MIN_PROTOC_VERSION.
@if ! command -v protoc &> /dev/null ; then \
echo "protoc not installed."; \
exit 1; \
fi; \
\
PROTOC_VERSION=$$(protoc --version | cut -d ' ' -f 2); \
\
if [[ $$(echo -e "$$PROTOC_VERSION\n$(MIN_PROTOC_VERSION)" | sort -V | head -n1) != $(MIN_PROTOC_VERSION) ]]; then \
echo "Error: protoc version $${PROTOC_VERSION} is < $(MIN_PROTOC_VERSION)"; \
exit 1; \
else \
echo "protoc version $${PROTOC_VERSION} is >= than $(MIN_PROTOC_VERSION)"; \
fi; \
protoc \
--proto_path=proto \
--python_out=lib \
--mypy_out=lib \
proto/streamlit/proto/*.proto
@# JS/TS protobuf generation
cd frontend/ ; yarn workspace @streamlit/protobuf run generate-protobuf
.PHONY: python-init
# Install Python dependencies and Streamlit in editable mode.
python-init:
pip_args=("--editable" "./lib");\
if [ "${INSTALL_DEV_REQS}" = "true" ] ; then\
pip_args+=("--requirement" "lib/dev-requirements.txt"); \
fi;\
if [ "${INSTALL_TEST_REQS}" = "true" ] ; then\
pip_args+=("--requirement" "lib/test-requirements.txt"); \
fi;\
if command -v "uv" > /dev/null; then \
echo "Running command: uv pip install $${pip_args[@]}"; \
uv pip install $${pip_args[@]}; \
else \
echo "Running command: pip install $${pip_args[@]}"; \
pip install $${pip_args[@]}; \
fi;\
if [ "${INSTALL_TEST_REQS}" = "true" ] && [ "${INSTALL_PLAYWRIGHT}" = "true" ] ; then\
python -m playwright install --with-deps; \
fi;
.PHONY: python-lint
# Lint and check formatting of Python files.
python-lint:
# Checks if the formatting is correct:
ruff format --check
# Run linter:
ruff check
.PHONY: python-format
# Format Python files.
python-format:
# Sort imports ( see https://docs.astral.sh/ruff/formatter/#sorting-imports )
ruff check --select I --fix
# Run code formatter
ruff format
.PHONY: python-tests
# Run Python unit tests.
python-tests:
cd lib; \
PYTHONPATH=. \
pytest -v -l \
-m "not performance" \
tests/
.PHONY: python-performance-tests
# Run Python performance tests.
python-performance-tests:
cd lib; \
PYTHONPATH=. \
pytest -v -l \
-m "performance" \
--benchmark-autosave \
--benchmark-storage file://../.benchmarks/pytest \
tests/
.PHONY: python-integration-tests
# Run Python integration tests. Requires `integration-requirements.txt` to be installed.
python-integration-tests:
cd lib; \
PYTHONPATH=. \
pytest -v -l \
--require-integration \
tests/
.PHONY: python-types
# Run the Python type checker.
python-types:
# Run ty type checker:
ty check
# Run mypy type checker:
mypy --config-file=mypy.ini
.PHONY: frontend-init
# Install all frontend dependencies.
frontend-init:
@cd frontend/ && { \
corepack enable yarn; \
if [ $$? -ne 0 ]; then \
echo "Error: 'corepack' command not found or failed to enable."; \
echo "Please ensure you are running the expected version of Node.js as defined in '.nvmrc'."; \
exit 1; \
fi; \
corepack install && yarn install --immutable; \
}
.PHONY: frontend
# Build the frontend.
frontend:
cd frontend/ ; yarn workspaces foreach --all --topological run build
rsync -av --delete --delete-excluded --exclude=reports \
frontend/app/build/ lib/streamlit/static/
# Move manifest.json to a location that can actually be served by the Tornado
# server's static asset handler.
mv lib/streamlit/static/.vite/manifest.json lib/streamlit/static
.PHONY: frontend-with-profiler
# Build the frontend with the profiler enabled.
frontend-with-profiler:
# Build frontend dependent libraries (excluding app and lib):
cd frontend/ ; yarn workspaces foreach --all --exclude @streamlit/app --exclude @streamlit/lib --topological run build
# Build the app with the profiler enabled:
cd frontend/ ; yarn workspace @streamlit/app buildWithProfiler
rsync -av --delete --delete-excluded --exclude=reports \
frontend/app/build/ lib/streamlit/static/
.PHONY: frontend-fast
# Build the frontend (as fast as possible).
frontend-fast:
cd frontend/ ; yarn workspaces foreach --recursive --topological --from @streamlit/app --exclude @streamlit/lib run build
rsync -av --delete --delete-excluded --exclude=reports \
frontend/app/build/ lib/streamlit/static/
.PHONY: frontend-dev
# Start the frontend development server.
frontend-dev:
cd frontend/ ; yarn start
.PHONY: frontend-lint
# Lint and check formatting of frontend files.
frontend-lint:
cd frontend/ ; yarn workspaces foreach --all run formatCheck
cd frontend/ ; yarn workspaces foreach --all run lint
.PHONY: frontend-types
# Run the frontend type checker.
frontend-types:
cd frontend/ ; yarn workspaces foreach --all run typecheck
.PHONY: frontend-format
# Format frontend files.
frontend-format:
cd frontend/ ; yarn workspaces foreach --all run format
.PHONY: frontend-tests
# Run frontend unit tests and generate coverage report.
frontend-tests:
cd frontend; TESTPATH=$(TESTPATH) yarn testCoverage
.PHONY: frontend-typesync
# Check for unsynced frontend types.
frontend-typesync:
cd frontend/ ; yarn workspaces foreach --all --exclude @streamlit/typescript-config run typesync:ci --dry=fail || (\
echo -e "\033[0;31mTypesync check failed. Run 'make update-frontend-typesync' to fix.\033[0m"; \
exit 1 \
)
.PHONY: update-frontend-typesync
# Installs missing typescript typings for dependencies.
update-frontend-typesync:
cd frontend/ ; yarn workspaces foreach --all --exclude @streamlit/typescript-config run typesync
cd frontend/ ; yarn
cd component-lib/ ; yarn typesync
cd component-lib/ ; yarn
.PHONY: update-snapshots
# Update e2e playwright snapshots based on the latest completed CI run.
update-snapshots:
python ./scripts/update_e2e_snapshots.py
.PHONY: update-snapshots-changed
# Update e2e playwright snapshots of changed e2e files based on the latest completed CI run.
update-snapshots-changed:
python ./scripts/update_e2e_snapshots.py --changed
.PHONY: update-material-icons
# Update material icons based on latest Google material symbol version.
update-material-icons:
python ./scripts/update_material_icon_font_and_names.py
.PHONY: update-emojis
# Update emojis based on latest emoji version.
update-emojis:
python ./scripts/update_emojis.py
.PHONY: update-notices
# Update the notices file (licenses of frontend assets and dependencies).
update-notices:
cd frontend; \
yarn licenses generate-disclaimer --production --recursive > ../NOTICES
./scripts/append_license.sh frontend/app/src/assets/fonts/Source_Code/Source-Code.LICENSE
./scripts/append_license.sh frontend/app/src/assets/fonts/Source_Sans/Source-Sans.LICENSE
./scripts/append_license.sh frontend/app/src/assets/fonts/Source_Serif/Source-Serif.LICENSE
./scripts/append_license.sh frontend/app/src/assets/img/Material-Icons.LICENSE
./scripts/append_license.sh frontend/app/src/assets/img/Open-Iconic.LICENSE
./scripts/append_license.sh frontend/lib/src/vendor/react-bootstrap-LICENSE.txt
./scripts/append_license.sh frontend/lib/src/vendor/fzy.js/fzyjs-LICENSE.txt
.PHONY: update-headers
# Update all license headers.
update-headers:
pre-commit run insert-license --all-files --hook-stage manual
pre-commit run license-headers --all-files --hook-stage manual
.PHONY: update-min-deps
# Update minimum dependency constraints file.
update-min-deps:
INSTALL_DEV_REQS=false INSTALL_TEST_REQS=false make python-init >/dev/null
python scripts/get_min_versions.py >scripts/assets/min-constraints-gen.txt
.PHONY: debug-e2e-test
# Run a playwright e2e test in debug mode. Use it via `make debug-e2e-test st_command_test.py`.
debug-e2e-test:
@if [[ ! "$(filter-out $@,$(MAKECMDGOALS))" == *"_test"* ]]; then \
echo "Error: Test script name must contain '_test' in the filename"; \
exit 1; \
fi
@echo "Running test: $(filter-out $@,$(MAKECMDGOALS)) in debug mode."
@TEST_SCRIPT=$$(echo $(filter-out $@,$(MAKECMDGOALS)) | sed 's|^e2e_playwright/||'); \
cd e2e_playwright && PWDEBUG=1 pytest $$TEST_SCRIPT --tracing on || ( \
echo "If you implemented changes in the frontend, make sure to call \`make frontend-fast\` to use the up-to-date frontend build in the test."; \
echo "You can find test-results in ./e2e_playwright/test-results"; \
exit 1 \
)
.PHONY: run-e2e-test
# Run a playwright e2e test. Use it via `make run-e2e-test st_command_test.py`.
run-e2e-test:
@if [[ ! "$(filter-out $@,$(MAKECMDGOALS))" == *"_test"* ]]; then \
echo "Error: Test script name must contain '_test' in the filename"; \
exit 1; \
fi
@echo "Running test: $(filter-out $@,$(MAKECMDGOALS))"
@TEST_SCRIPT=$$(echo $(filter-out $@,$(MAKECMDGOALS)) | sed 's|^e2e_playwright/||'); \
cd e2e_playwright && pytest $$TEST_SCRIPT --tracing retain-on-failure --reruns 0 || ( \
echo "If you implemented changes in the frontend, make sure to call \`make frontend-fast\` to use the up-to-date frontend build in the test."; \
echo "You can find test-results in ./e2e_playwright/test-results"; \
exit 1 \
)
.PHONY: trace-e2e-test
# Run e2e test with tracing and view it. Use via `make trace-e2e-test <test_file.py>::<test_func>`.
trace-e2e-test:
@if [[ -z "$(filter-out $@,$(MAKECMDGOALS))" ]]; then \
echo "Error: Please specify a single test to run"; \
echo "Usage: make trace-e2e-test <test_file.py>::<test_function>"; \
echo "Example: make trace-e2e-test st_audio_input_test.py::test_audio_input_renders"; \
exit 1; \
fi
@TEST_ARG=$$(echo $(filter-out $@,$(MAKECMDGOALS)) | sed 's|^e2e_playwright/||'); \
if [[ ! "$$TEST_ARG" == *"::"* ]]; then \
echo "Error: You must specify a single test function, not an entire test file"; \
echo "Usage: make trace-e2e-test <test_file.py>::<test_function>"; \
echo "Example: make trace-e2e-test st_audio_input_test.py::test_audio_input_renders"; \
exit 1; \
fi; \
echo "Clearing previous traces..."; \
rm -rf e2e_playwright/test-results/traces; \
mkdir -p e2e_playwright/test-results/traces; \
echo "Running test with tracing: $$TEST_ARG"; \
(cd e2e_playwright && pytest $$TEST_ARG --tracing=on --output=test-results/traces || true); \
echo ""; \
echo "Launching trace viewer..."; \
TRACE_FILE=$$(find e2e_playwright/test-results/traces -name "trace.zip" -type f 2>/dev/null | head -n 1); \
if [[ -n "$$TRACE_FILE" ]]; then \
python -m playwright show-trace "$$TRACE_FILE"; \
else \
echo "No trace file found. Check e2e_playwright/test-results/traces/ directory."; \
fi
.PHONY: lighthouse-tests
# Run Lighthouse performance tests.
lighthouse-tests:
cd frontend/app; \
yarn run lighthouse:run
.PHONY: bare-execution-tests
# Run all e2e tests in bare mode.
bare-execution-tests:
PYTHONPATH=. \
python3 scripts/run_bare_execution_tests.py
.PHONY: cli-smoke-tests
# Run CLI smoke tests.
cli-smoke-tests:
python3 scripts/cli_smoke_tests.py
.PHONY: autofix
# Autofix linting and formatting errors.
autofix:
# Python fixes:
make python-format
ruff check --fix
# JS fixes:
make frontend-init
make frontend-format
cd frontend/ ; yarn workspaces foreach --all run lint --fix
# Dedupe yarn.lock
cd frontend ; yarn dedupe
# Other fixes:
make update-notices
# Run all pre-commit fixes but not fail if any of them don't work.
pre-commit run --all-files --hook-stage manual || true
.PHONY: package
# Create Python wheel files in `dist/`.
package: init frontend
# Get rid of the old build and dist folders to make sure that we clean old js and css.
rm -rfv lib/build lib/dist
cd lib ; python3 setup.py bdist_wheel sdist
.PHONY: conda-package
# Create conda distribution files.
conda-package: init
if [ "${SNOWPARK_CONDA_BUILD}" = "1" ] ; then\
echo "Creating Snowpark conda build, so skipping building frontend assets."; \
else \
make frontend; \
fi
rm -rf lib/conda-recipe/dist
mkdir lib/conda-recipe/dist
# This can take upwards of 20 minutes to complete in a fresh conda installation! (Dependency solving is slow.)
# NOTE: Running the following command requires both conda and conda-build to
# be installed.
GIT_HASH=$$(git rev-parse --short HEAD) conda build lib/conda-recipe --output-folder lib/conda-recipe/dist
| 5,754
|
streamlit
|
streamlit/README.md
|
<br>
<img src="https://user-images.githubusercontent.com/7164864/217935870-c0bc60a3-6fc0-4047-b011-7b4c59488c91.png" alt="Streamlit logo" style="margin-top:50px"></img>
# Welcome to Streamlit 👋
**A faster way to build and share data apps.**
## What is Streamlit?
Streamlit lets you transform Python scripts into interactive web apps in minutes, instead of weeks. Build dashboards, generate reports, or create chat apps. Once you’ve created an app, you can use our [Community Cloud platform](https://streamlit.io/cloud) to deploy, manage, and share your app.
### Why choose Streamlit?
- **Simple and Pythonic:** Write beautiful, easy-to-read code.
- **Fast, interactive prototyping:** Let others interact with your data and provide feedback quickly.
- **Live editing:** See your app update instantly as you edit your script.
- **Open-source and free:** Join a vibrant community and contribute to Streamlit's future.
## Installation
Open a terminal and run:
```bash
$ pip install streamlit
$ streamlit hello
```
If this opens our sweet _Streamlit Hello_ app in your browser, you're all set! If not, head over to [our docs](https://docs.streamlit.io/get-started) for specific installs.
The app features a bunch of examples of what you can do with Streamlit. Jump to the [quickstart](#quickstart) section to understand how that all works.
<img src="https://user-images.githubusercontent.com/7164864/217936487-1017784e-68ec-4e0d-a7f6-6b97525ddf88.gif" alt="Streamlit Hello" width=500 href="none"></img>
## Quickstart
### A little example
Create a new file named `streamlit_app.py` in your project directory with the following code:
```python
import streamlit as st
x = st.slider("Select a value")
st.write(x, "squared is", x * x)
```
Now run it to open the app!
```
$ streamlit run streamlit_app.py
```
<img src="https://user-images.githubusercontent.com/7164864/215172915-cf087c56-e7ae-449a-83a4-b5fa0328d954.gif" width=300 alt="Little example"></img>
### Give me more!
Streamlit comes in with [a ton of additional powerful elements](https://docs.streamlit.io/develop/api-reference) to spice up your data apps and delight your viewers. Some examples:
<table border="0">
<tr>
<td>
<a target="_blank" href="https://docs.streamlit.io/develop/api-reference/widgets">
<img src="https://user-images.githubusercontent.com/7164864/217936099-12c16f8c-7fe4-44b1-889a-1ac9ee6a1b44.png" style="max-height:150px; width:auto; display:block;">
</a>
</td>
<td>
<a target="_blank" href="https://docs.streamlit.io/develop/api-reference/data/st.dataframe">
<img src="https://user-images.githubusercontent.com/7164864/215110064-5eb4e294-8f30-4933-9563-0275230e52b5.gif" style="max-height:150px; width:auto; display:block;">
</a>
</td>
<td>
<a target="_blank" href="https://docs.streamlit.io/develop/api-reference/charts">
<img src="https://user-images.githubusercontent.com/7164864/215174472-bca8a0d7-cf4b-4268-9c3b-8c03dad50bcd.gif" style="max-height:150px; width:auto; display:block;">
</a>
</td>
<td>
<a target="_blank" href="https://docs.streamlit.io/develop/api-reference/layout">
<img src="https://user-images.githubusercontent.com/7164864/217936149-a35c35be-0d96-4c63-8c6a-1c4b52aa8f60.png" style="max-height:150px; width:auto; display:block;">
</a>
</td>
<td>
<a target="_blank" href="https://docs.streamlit.io/develop/concepts/multipage-apps">
<img src="https://user-images.githubusercontent.com/7164864/215173883-eae0de69-7c1d-4d78-97d0-3bc1ab865e5b.gif" style="max-height:150px; width:auto; display:block;">
</a>
</td>
<td>
<a target="_blank" href="https://streamlit.io/gallery">
<img src="https://user-images.githubusercontent.com/7164864/215109229-6ae9111f-e5c1-4f0b-b3a2-87a79268ccc9.gif" style="max-height:150px; width:auto; display:block;">
</a>
</td>
</tr>
<tr>
<td>Input widgets</td>
<td>Dataframes</td>
<td>Charts</td>
<td>Layout</td>
<td>Multi-page apps</td>
<td>Fun</td>
</tr>
</table>
Our vibrant creators community also extends Streamlit capabilities using 🧩 [Streamlit Components](https://streamlit.io/components).
## Get inspired
There's so much you can build with Streamlit:
- 🤖 [LLMs & chatbot apps](https://streamlit.io/gallery?category=llms)
- 🧬 [Science & technology apps](https://streamlit.io/gallery?category=science-technology)
- 💬 [NLP & language apps](https://streamlit.io/gallery?category=nlp-language)
- 🏦 [Finance & business apps](https://streamlit.io/gallery?category=finance-business)
- 🗺 [Geography & society apps](https://streamlit.io/gallery?category=geography-society)
- and more!
**Check out [our gallery!](https://streamlit.io/gallery)** 🎈
## Community Cloud
Deploy, manage and share your apps for free using our [Community Cloud](https://streamlit.io/cloud)! Sign-up [here](https://share.streamlit.io/signup). <br><br>
<img src="https://user-images.githubusercontent.com/7164864/214965336-64500db3-0d79-4a20-8052-2dda883902d2.gif" width="400"></img>
## Resources
- Explore our [docs](https://docs.streamlit.io) to learn how Streamlit works.
- Ask questions and get help in our [community forum](https://discuss.streamlit.io).
- Read our [blog](https://blog.streamlit.io) for tips from developers and creators.
- Extend Streamlit's capabilities by installing or creating your own [Streamlit Components](https://streamlit.io/components).
- Help others find and play with your app by using the Streamlit GitHub badge in your repository:
```markdown
[](URL_TO_YOUR_APP)
```
[](https://share.streamlit.io/streamlit/roadmap)
## Contribute
🎉 Thanks for your interest in helping improve Streamlit! 🎉
Before contributing, please read our guidelines here: https://github.com/streamlit/streamlit/wiki/Contributing
## License
Streamlit is completely free and open-source and licensed under the [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) license.
| 2,248
|
streamlit
|
streamlit/SECURITY.md
|
# Security Policy
## Supported Versions
| Version | Supported |
| --------- | --------- |
| >= 1.11.1 | ✅ |
</br>
Please refer to the Snowflake [HackerOne program](https://hackerone.com/snowflake?type=team) for our security policies and for reporting any security vulnerabilities.
| 90
|
streamlit
|
streamlit/agent-knowledge/INDEX.md
|
---
last_updated: 2025-11-05
---
# Agent Knowledge Base Index
Central registry of resources available to AI agents working on Streamlit.
## Available Resources
### [Processes](processes/)
Development workflows and procedures:
- [pr-creation/](processes/pr-creation/) - Complete PR creation workflow with guidance on filling `.github/pull_request_template.md` (see README.md for details)
### [Guides](references/guides/)
System overviews and comprehensive documentation (e.g., layout system, caching, state management)
### [Features](references/features/)
Feature development artifacts (specs + implementation plans) organized by area. Not tracked in git.
## Contributing
See [README.md](README.md#contributing) for contribution guidelines.
## See Also
- [README.md](README.md) - Purpose and usage guide for this directory
- [../AGENTS.md](../AGENTS.md) - Top-level agent repo overview
---
| 250
|
streamlit
|
streamlit/agent-knowledge/README.md
|
# Agent Knowledge Base
This directory contains documentation and guides designed for AI agents working on the Streamlit codebase.
## Purpose
Tool-agnostic knowledge base for AI-assisted development. Works with any AI tool (Cursor, Cline, Aider, etc.) and any task type (commands, pipelines, ad-hoc prompts).
## Quick Start
📖 **[See INDEX.md for a catalog of available resources](INDEX.md)**
## How to Use
1. **Starting a task?** Check [INDEX.md](INDEX.md) for relevant resources
2. **Creating a PR?** Use `.github/pull_request_template.md` and fill according to [processes/pr-creation/](processes/pr-creation/)
3. **Need help with a specific workflow?** Browse the [processes/](processes/) directory
## Contributing
### Local Experimentation
Keep files local while developing by using these patterns (automatically ignored by git):
- `*.local.md` - Individual local files (e.g., `draft-guide.local.md`, `notes.local.md`)
- `local/` - Directory for local experiments and work in progress
### Adding Shared Resources
To add a resource for the team:
1. Create the resource following existing patterns (if any exist)
2. Add YAML frontmatter to set team expectations:
```yaml
---
status: stable | experimental
last_updated: YYYY-MM-DD
---
```
- `status: experimental` - Workflow being developed, team feedback welcome
- `status: stable` - Established, reviewed workflow
3. Update INDEX.md to make it discoverable
## Relationship to Other Agent Resources
| Resource | When Loaded | Scope | Tool Support |
| --------------------------- | --------------------------- | ----------------------- | --------------- |
| **AGENTS.md** | Every prompt (always-on) | Succinct, universal | All tools |
| **agent-knowledge/** (here) | On-demand (when referenced) | Detailed, task-specific | All tools |
| **.cursor/commands/** | Executed by user | Executable workflows | Cursor-specific |
**Key Distinctions:**
- **AGENTS.md**: Always injected → must be brief
- **agent-knowledge/**: Referenced on-demand → can be comprehensive
- **.cursor/commands/**: Executable workflows → tool-specific
| 703
|
streamlit
|
streamlit/agent-knowledge/processes/pr-creation/README.md
|
---
status: stable
last_updated: 2025-11-19
---
# PR Creation Process
Reference materials for creating pull requests in the Streamlit repository.
## The PR Template
**Location**: `.github/pull_request_template.md` (canonical source)
## Available Guides
- [writing-principles.md](./writing-principles.md) - General writing style (brevity, commit messages, PR titles)
- [describe-changes-guide.md](./describe-changes-guide.md) - How to describe what changed (selectivity, what to include/omit)
- [testing-plan-guide.md](./testing-plan-guide.md) - How to document tests in PRs
- [branch-naming.md](./branch-naming.md) - Branch naming conventions
- [labeling-guide.md](./labeling-guide.md) - Required PR labels
## See Also
- [../../INDEX.md](../../INDEX.md) - Agent knowledge base index
- [.github/pull_request_template.md](../../../.github/pull_request_template.md) - The canonical PR template
| 281
|
streamlit
|
streamlit/agent-knowledge/processes/pr-creation/branch-naming.md
|
---
status: experimental
last_updated: 2025-11-05
---
# Branch Naming - Best Practices
## Format
```
{type}/{brief-description}
```
## Types
- `feature` - New features or functionality
- `fix` - Bug fixes
- `refactor` - Code refactoring
- `chore` - Maintenance tasks (dependencies, tooling, etc.)
- `docs` - Documentation changes
## Guidelines
**Good branch names:**
- Descriptive and specific (3-6 words typical, up to 8 for complex changes)
- Use kebab-case (hyphens between words)
- Clearly indicate what is being changed and why
- Include the component/area being modified when helpful
- Avoid ticket/issue numbers (use PR description for that)
**Format patterns:**
- `{type}/{action}-{component}-{detail}` - e.g., `feature/add-height-plotly-charts`
- `{type}/{area}-{specific-change}` - e.g., `fix/dataframe-memory-leak-scrolling`
- `{type}/{what-is-changing}` - e.g., `refactor/arrow-table-conversion-logic`
## Examples
- `feature/add-height-parameter-plotly-charts` - Adding new parameter to specific component
- `fix/dataframe-memory-leak-large-datasets` - Fixing specific bug with context
- `refactor/element-width-height-logic` - Refactoring specific area of codebase
- `chore/update-react-dependencies` - Maintenance task with specific scope
- `docs/api-reference-layout-parameters` - Documentation update for specific section
| 426
|
streamlit
|
streamlit/agent-knowledge/processes/pr-creation/describe-changes-guide.md
|
---
status: stable
last_updated: 2025-12-02
---
# Guide: Describing Changes
Use this guide for PR template sections that ask what changed (e.g., "Describe your changes").
## Content Guidelines
**Keep it brief:** 2-4 bullets maximum for listing changes.
**List only impactful changes** - not every file touched.
**Omit obvious details** - don't explain what's clear from reading the code.
**Explain non-obvious decisions** - only include implementation details that aren't obvious.
## Selectivity Checklist
Before including a change, ask:
1. **Is this obvious?** → Omit it
2. **Is this a standard pattern?** (tests, types, validation) → Omit it
3. **Is this the most impactful change?** → Include it
4. **Does this involve a non-obvious decision?** → Include it with explanation
## Example: Feature Adding a Parameter
**What to include:**
- ✓ New parameter added (the main change)
- ✓ Deprecation of old parameter (impacts users)
- ✓ Non-obvious behavior (special handling, fallbacks)
**What to omit:**
- ✗ Added tests (obvious)
- ✗ Updated types (obvious)
- ✗ Added validation (obvious)
- ✗ Updated proto (implementation detail)
- ✗ Fixed linting (housekeeping)
## Good vs Bad Examples
**Good (selective, highlights what matters):**
> Adds `height` parameter to `st.plotly_chart()` using `Height` type system.
>
> - Added `height` parameter with default `"stretch"`
> - Deprecates `use_container_height` (removed after 2025-12-31)
**Bad (lists every change):**
> - Added `height: Height = "stretch"` parameter to st.plotly_chart signature
> - Updated layout config dataclass to accept height parameter
> - Added validation for height parameter values
> - Updated proto message to include height field
> - Added unit tests for height parameter
> - Added E2E tests for height visual behavior
> - Updated type hints in plotly_chart.py
**Why bad:** Most of these are obvious. Only list what's non-obvious or impactful.
## Implementation Notes
If the change involves non-obvious behavior, add a brief explanation:
**Good:**
> When `height="content"`, extracts height from native Plotly figure if specified, falls back to `"stretch"` otherwise.
**Bad:**
> The height parameter is validated to ensure only valid values are accepted.
**Why bad:** This is obvious - of course parameters are validated.
| 646
|
streamlit
|
streamlit/agent-knowledge/processes/pr-creation/labeling-guide.md
|
---
status: experimental
last_updated: 2025-11-05
---
# PR Labeling Guide
All Streamlit PRs must have the following labels applied.
## Required Labels
### 1. Security Assessment
- `security-assessment-completed` - Required for all PRs
### 2. Impact Classification
Choose **one**:
- `impact:users` - Changes will affect behavior for users
- `impact:internal` - Changes will not affect user behavior
### 3. Change Type
Choose **one**:
- `change:feature` - New features or feature enhancements
- `change:bugfix` - Bug fixes
- `change:chore` - Small changes for repo maintenance
- `change:refactor` - Refactoring changes to improve code quality
- `change:other` - Things that don't fit other categories
- `change:docs` - Documentation updates, e.g. docstring only changes
## Label Combination Examples
**For new features:**
- `security-assessment-completed`
- `impact:users` (changes user-facing API)
- `change:feature` (adds new functionality)
**For internal refactoring:**
- `security-assessment-completed`
- `impact:internal` (no user behavior change)
- `change:refactor` (improves code quality)
**For bug fixes:**
- `security-assessment-completed`
- `impact:users` (fixes user-facing issue)
- `change:bugfix` (fixes a bug)
**For documentation updates:**
- `security-assessment-completed`
- `impact:internal` (no behavior change)
- `change:docs` (documentation)
| 410
|
streamlit
|
streamlit/agent-knowledge/processes/pr-creation/testing-plan-guide.md
|
---
status: experimental
last_updated: 2025-11-05
---
# How to Fill In the Testing Plan
Guide for documenting tests in PR descriptions.
## Detect Test Changes in Git Diff
Check for modified/added test files:
**Python unit tests:**
- Pattern: `lib/tests/**/*.py`
- Example: `lib/tests/streamlit/elements/plotly_chart_test.py`
**Frontend unit tests:**
- Pattern: `frontend/**/*.test.ts` or `frontend/**/*.test.tsx`
- Example: `frontend/lib/src/components/elements/PlotlyChart/PlotlyChart.test.tsx`
**E2E tests:**
- Pattern: `e2e_playwright/**/*_test.py`
- Example: `e2e_playwright/st_plotly_chart_test.py`
## Fill In PR Template Checklist
Based on files changed:
```markdown
- [x] Unit Tests (JS and/or Python) - If lib/tests/ or frontend/\*_/_.test.\* files changed
- [x] E2E Tests - If e2e_playwright/ files changed
- [ ] Manual testing completed - Leave unchecked (user will complete if applicable)
- [x] Explanation of why no additional tests are needed - If no test files changed
```
## Describe Testing in PR
**If tests were added/modified:**
List the test files and what they cover:
```markdown
**Testing:**
- `lib/tests/streamlit/elements/plotly_chart_test.py` - Tests height parameter functionality
- `e2e_playwright/st_plotly_chart_test.py` - Visual regression tests for height behavior
```
**If no tests needed:**
Explain why:
```markdown
**No Additional Tests:**
Documentation-only changes, no behavior modifications.
```
## Detection Logic for AI Agents
```python
# Pseudo-code for detecting test types from git diff
has_python_tests = any("lib/tests/" in file for file in changed_files)
has_frontend_tests = any(file.endswith(('.test.ts', '.test.tsx')) for file in changed_files)
has_e2e_tests = any("e2e_playwright/" in file for file in changed_files)
# Check boxes based on what can be detected
checklist = {
"unit_tests": has_python_tests or has_frontend_tests,
"e2e_tests": has_e2e_tests,
"manual_testing": False, # Always leave unchecked - user fills in
"no_tests_needed": not (has_python_tests or has_frontend_tests or has_e2e_tests),
}
```
| 707
|
streamlit
|
streamlit/agent-knowledge/processes/pr-creation/writing-principles.md
|
---
status: stable
last_updated: 2025-12-02
---
# Writing Principles for PRs
**Core principle: Highlight what matters. Omit the obvious.**
Don't list every change - focus on the most impactful. Don't explain what's obvious from reading the code - only explain non-obvious decisions.
## Commit Messages
**Format:**
```
<imperative verb> <what> <where>
Optional body with technical details.
```
**Rules:**
- First line: ≤50 characters
- Use imperative mood ("Add" not "Added" or "Adds")
- No periods at end of first line
- Body: ≤72 characters per line (if needed)
**Good examples:**
```
Add height parameter to plotly charts
Fix memory leak in dataframe scrolling
Refactor layout config validation logic
```
**Bad examples (too verbose):**
```
✗ Added a new height parameter feature to the plotly chart component to enable users to control chart dimensions
✗ This commit fixes the memory leak that was occurring when users scrolled through large dataframes
```
## PR Titles
**Format:**
```
[type] lowercase description of change
```
**Rules:**
- Start with change type in brackets: `[feature]`, `[fix]`, `[refactor]`, `[chore]`, `[docs]`
- ≤80 characters total
- Lowercase after the bracket
- Descriptive, not marketing
- Match commit message content if single commit
**Good examples:**
```
[feature] add height parameter to plotly charts
[fix] extra padding on button
[refactor] layout config validation logic
[chore] update dependencies
[docs] clarify st.cache_data usage
```
**Bad examples:**
```
✗ Exciting new feature: height parameter support for beautiful plotly charts!
✗ This PR fixes a critical memory leak issue that users were experiencing
✗ Add height parameter (missing [type] prefix)
```
## General Content Principles
**What NOT to include:**
- ✗ "Added tests" (obvious)
- ✗ "Updated type hints" (obvious)
- ✗ "Added validation" (obvious)
- ✗ "Updated documentation" (obvious)
- ✗ "Fixed linting errors" (obvious)
**Don't explain obvious behavior:**
- ✗ "Parameters are validated to ensure correctness"
- ✗ "Added error handling for edge cases"
- ✗ "Code follows existing patterns"
**DO explain non-obvious decisions:**
- ✓ "Deprecates `use_container_height` (removed after 2025-12-31)"
- ✓ "When `height="content"`, extracts from native figure if specified"
- ✓ "Uses `rem` units instead of `px` for responsive sizing"
## No Meta-Commentary
Skip phrases like:
- "This PR..."
- "We have..."
- "I added..."
Just state what changed directly.
| 726
|
streamlit
|
streamlit/agent-knowledge/references/guides/streamlit-layout-feature.md
|
---
status: stable
last_updated: 2025-11-05
---
# Overview
This document includes details of the implementation of the layout feature for Streamlit.
The layout feature includes:
- Width parameters for widgets and elements.
- Height parameters for widgets and elements.
- A container element for flexbox layouts (st.container).
The layout system is still under development and some elements may still use an older style or may not have all of the described features implemented.
# Description of Expected Behaviour
## Width
All Streamlit elements have a width parameter that allows users developing layouts to configure its width.
Elements support a subset of the modes or all of them.
There are three modes:
1. Stretch
When the width on an element is set to "stretch", the element should expand to fill available horizontal space according to these rules:
- The element's display width should not exceed the width of its parent container.
Examples:
```python
import streamlit as st
import numpy as np
from numpy import typing as npt
img: npt.NDArray[np.int64] = np.repeat(0, 75000).reshape(300, 250)
with st.container(horizontal=True, key="horizontal_parent_container", width=300):
# The width of this image should expand to fill the horizontal_parent_container (minus some padding).
# The width of this image should never be more than 300px because that is the width of the parent.
st.image(img, width="stretch")
```
- When the element is in a row inside a horizontal container, space should be shared with other elements.
Examples:
```python
import streamlit as st
import numpy as np
from numpy import typing as npt
img: npt.NDArray[np.int64] = np.repeat(0, 75000).reshape(300, 250)
with st.container(horizontal=True, key="horizontal_parent_container"):
# The image and the markdown element should share the space equally. At typical screen widths, we expect to see
# both elements on one row.
st.image(img, width="stretch")
# st.markdown will have internal whitespace on wide screens.
st.markdown("HELLO DARLING", width="stretch")
```
2. Content
When the width on an element is set to "content", the width of the element should be based on the contents of the element.
3. Integer
When an integer width is provided, the element will be that width in pixels.
## Height
All Streamlit elements have a height parameter that allows users developing layouts to configure its height.
Elements support a subset of the available modes or all of them.
The modes are:
1. Stretch
When the height on an element is set to "stretch", the element should expand to fill available vertical space according to these rules:
- The element's display height should not exceed the height of its parent container.
Examples:
```python
with st.container(key="vertical_parent_container", height=300):
# The height of the text area should expand to fill the parent container (minus some padding).
# The height of the text area should never be more than 300px because that is the height of the parent container.
st.text_area("enter your message here", height="stretch")
```
- When the element is in a column inside a vertical container, space should be shared with other elements.
Examples:
```python
with st.container(key="vertical_parent_container", height=400):
# The text area and code block should share the vertical space equally.
st.text_area("Enter your message here", height="stretch")
# The code block will also stretch to share remaining space.
st.code("print('Additional content below')", height="stretch")
```
2. Content
When the height on an element is set to "content", the height of the element should be based on the contents of the element.
3. Integer
When an integer height is provided, the element will be that height in pixels.
4. Auto
Some elements have this mode which indicates customized behavior for the element. This mode is only available for specific elements that display data tables.
Examples:
- `st.dataframe` and `st.data_editor` support this height mode. When `height="auto"` (the default), these elements automatically size their height to show at most 10 rows of data, optimizing the display for the dataset size.
# Technical Implementation Details
## Architecture Flow
- Python API → Proto messages → Frontend CSS
**Key Implementation Layers:**
- **Python**: `lib/streamlit/elements/`, `lib/streamlit/delta_generator.py`
- **Proto**: `proto/streamlit/proto/{Element,WidthConfig,HeightConfig}.proto`
- **Frontend**: `frontend/lib/src/components/core/{Block,Layout}/` (ElementNodeRenderer, StyledElementContainerLayoutWrapper, useLayoutStyles)
## Python Layer
The API is provided to the user in the python function corresponding to the element.
Example:
```python
def metric(
# ... other parameters ...
*,
# ... other keyword-only parameters ...
width: Width = "stretch",
height: Height = "content",
# ... other keyword-only parameters ...
) -> DeltaGenerator:
```
The width and height are validated using common utility functions, then a LayoutConfig object is
created and provided to the `_enqueue` method on the Delta Generator.
validate_height(height, allow_content=True)
validate_width(width, allow_content=True)
layout_config = LayoutConfig(width=width, height=height)
return self.dg._enqueue("metric", metric_proto, layout_config=layout_config)
In `_enqueue`, the layout config is converted to proto messages:
```python
if layout_config:
if layout_config.height is not None:
msg.delta.new_element.height_config.CopyFrom(
get_height_config(layout_config.height)
)
if layout_config.width is not None:
msg.delta.new_element.width_config.CopyFrom(
get_width_config(layout_config.width)
)
```
The `get_height_config` and `get_width_config` utility functions convert the Python string/int values into the appropriate proto message structure.
## Proto Messages
Proto messages communicate layout preferences from Python to frontend. The layout system uses three related messages:
```protobuf
// Element contains layout config fields
message Element {
optional streamlit.HeightConfig height_config = 57;
optional streamlit.WidthConfig width_config = 58;
// ... other element types ...
}
// Layout configuration messages (see CSS conversion table in useLayoutStyles section)
message WidthConfig {
oneof width_spec {
bool use_stretch = 1;
bool use_content = 2;
uint32 pixel_width = 3;
float rem_width = 4; // Used for literal sizes (e.g., st.space)
}
}
message HeightConfig {
oneof height_spec {
bool use_stretch = 1;
bool use_content = 2;
uint32 pixel_height = 3;
float rem_height = 4; // Used for literal sizes (e.g., st.space)
}
}
```
## Frontend Styling
Element node rendering is performed in `ElementNodeRenderer.tsx`.
During rendering, each element is wrapped in a `StyledElementContainerLayoutWrapper`. The layout styles are primarily applied to this wrapper container. Some elements require further stylings in their react components to implement the different height/width modes. Keeping the styling in the shared layers is preferred. Styles are computed in the hook `useLayoutStyles` based on the information provided in the proto files. This hook also implements backwards compatibly logic for previous versions of the proto messages.
### Element Rendering Flow
In `ElementNodeRenderer.tsx`, layout config is passed to elements and they're wrapped in the layout container:
```typescript
// Layout config passed to elements for custom internal styling
const elementProps = {
widthConfig: node.element.widthConfig,
heightConfig: node.element.heightConfig,
// ... other props
}
// Elements wrapped in layout wrapper
<StyledElementContainerLayoutWrapper node={node}>
<RawElementNodeRenderer {...props} />
</StyledElementContainerLayoutWrapper>
```
### Layout Wrapper Implementation
The `StyledElementContainerLayoutWrapper` applies element categories and overrides:
```typescript
// Element categories determine minimum widths in horizontal layouts
if (LARGE_STRETCH_BEHAVIOR.includes(node.element.type)) {
minStretchBehavior = "14rem"; // Complex elements: charts, dataframes, media
} else if (MEDIUM_STRETCH_BEHAVIOR.includes(node.element.type)) {
minStretchBehavior = "8rem"; // Form inputs: textInput, selectbox, slider
}
// Default: "fit-content" - elements shrink to natural content size
// Element-specific overrides (example: textArea stretch)
if (
node.element.type === "textArea" &&
node.element.heightConfig?.useStretch
) {
styleOverrides = { height: "100%", flex: "1 1 8rem" };
}
// Apply layout styles
const styles = useLayoutStyles({
element,
styleOverrides,
minStretchBehavior,
});
```
**Element Categories:**
- **LARGE_STRETCH_BEHAVIOR** (14rem minimum): Complex elements like `arrowDataFrame`, `plotlyChart`, `graphvizChart`, `video`, `fileUploader`, etc.
- **MEDIUM_STRETCH_BEHAVIOR** (8rem minimum): Form inputs like `textInput`, `selectbox`, `slider`, `textArea`, `numberInput`, etc.
These categories control the minimum flex-basis in horizontal layouts to prevent elements from shrinking too small when sharing space. They also provide min-width protection when elements are inside content-width containers.
### useLayoutStyles Hook
The `useLayoutStyles` hook (in `useLayoutStyles.ts`) converts proto config to CSS properties using these core patterns:
**Complete Proto to CSS Conversion (Default Behavior):**
| Proto Field | Default CSS Properties | Context |
| -------------------------- | -------------------------------------------- | ----------------------------------------------------- |
| `widthConfig.useStretch` | `width: "100%"` + `flex: "1 1 ${minWidth}"` | Horizontal layouts apply flex with element categories |
| `widthConfig.useContent` | `width: "fit-content"` | Element shrinks to natural content size |
| `widthConfig.pixelWidth` | `width: "${pixels}px"` | Fixed width in pixels |
| `heightConfig.useStretch` | `height: "100%"` + `flex: "1 1 auto"` | Vertical layouts apply flex properties |
| `heightConfig.useContent` | `height: "auto"` | Element uses natural content height |
| `heightConfig.pixelHeight` | `height: "${pixels}px"` + `overflow: "auto"` | Fixed height with scroll if needed |
**Min-Width Protection in Content-Width Containers:**
When an element with `width="stretch"` is inside a content-width container (tracked via `FlexContext.isInContentWidthContainer`), min-width is automatically applied using the `minStretchBehavior` value. This prevents elements from becoming too narrow when the container shrinks to fit its content.
The min-width respects parent container constraints (via `calculateMinWidthWithParentConstraint`) to avoid overflow issues.
**Element-Specific Overrides:** Some elements modify these defaults in `StyledElementContainerLayoutWrapper` (see Layout Wrapper examples above for specific cases like `textArea` stretch mode).
**Backwards Compatibility:** Supports older proto formats through `subElement` parameter for cached messages.
# Debugging
## Common Failure Modes
1. Height not stretching correctly.
The element height does not fill the parent container height, instead it fits the content.
Look for:
- HTML elements interior to the component that may need `height: 100%` to stretch.
- If it is a graph it may need the container height provided to the graphing library. The `useCalculatedDimensions` hook (in `frontend/lib/src/hooks/useCalculatedDimensions.ts`) can be utilized to measure the container height.
| 3,444
|
streamlit
|
streamlit/component-lib/.yarnrc.yml
|
nodeLinker: node-modules
| 8
|
streamlit
|
streamlit/component-lib/README.md
|
# Streamlit Component Library
An npm package that provides support code for creating [Streamlit Components](https://docs.streamlit.io/develop/concepts/custom-components).
The fastest way to start writing a Streamlit Component is to use our [Component Template repo](https://github.com/streamlit/component-template), which contains templates and example code.
| 82
|
streamlit
|
streamlit/component-lib/RELEASE_NOTES.md
|
<!--
Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
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.
-->
# Release notes
# 2.0.0
This release has no significant changes to our API, but we bump the major version as
the [`apache-arrow`](https://www.npmjs.com/package/apache-arrow) library is updated, which may affect users of the library. For details, see: [Apache Arrow Releases](https://arrow.apache.org/release/).
Moreover, it is worth adding that:
- The new version of `apache-arrow` requires a newer version of Typescript to work, but thanks to that you can also use `create-react-script` 5 and newer and the latest versions of NodeJS.
- We dropped use of [`event-target-shim`](https://www.npmjs.com/package/event-target-shim) as modern browsers no longer need it.
## List of commits
- [`21e7beeae`](https://github.com/streamlit/streamlit/commit/21e7beeae) Bump dependencies of component-lib (#6830)
- [`1e6a3e45e`](https://github.com/streamlit/streamlit/commit/1e6a3e45e) Add tests for component-lib (#6580)
- [`e43f64c72`](https://github.com/streamlit/streamlit/commit/e43f64c72) fix: upgrade command-line-args from 5.0.2 to 5.2.1 (#6258)
- [`3bb2243ec`](https://github.com/streamlit/streamlit/commit/3bb2243ec) fix: upgrade flatbuffers from 1.11.0 to 1.12.0 (#6259)
- [`fe8fd4f5c`](https://github.com/streamlit/streamlit/commit/fe8fd4f5c) fix: upgrade multiple dependencies with Snyk (#6262)
- [`0dfd31940`](https://github.com/streamlit/streamlit/commit/0dfd31940) Update license headers (#5143)
- [`76859d67b`](https://github.com/streamlit/streamlit/commit/76859d67b) fix: Allow renderData.args to be typed (#5205)
- [`c8f2db61f`](https://github.com/streamlit/streamlit/commit/c8f2db61f) Fix typos (#5082)
- [`f85a0feac`](https://github.com/streamlit/streamlit/commit/f85a0feac) Fix build issues due to linting errors (#4637)
- [`a91272018`](https://github.com/streamlit/streamlit/commit/a91272018) Bump ansi-regex from 4.1.0 to 4.1.1 in /component-lib (#4558)
- [`d44b16290`](https://github.com/streamlit/streamlit/commit/d44b16290) Update years in all license headers (#4291)
| 884
|
streamlit
|
streamlit/component-lib/jest.config.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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.
*/
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/_7/mm9vqb4d5jsbb9v9xsfxy4600000gn/T/jest_dx",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["src/**/*.{ts,tsx}"],
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: [
"<rootDir>/src/setupTests.ts",
"@testing-library/jest-dom/extend-expect",
],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "jsdom",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
| 1,938
|
streamlit
|
streamlit/component-lib/package.json
|
{
"name": "streamlit-component-lib",
"version": "2.0.0",
"description": "Support code for Streamlit Components",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "tsc",
"test": "jest ./src",
"typesync": "typesync",
"typesync:ci": "typesync --dry=fail"
},
"repository": {
"type": "git",
"url": "git+https://github.com/streamlit/streamlit.git"
},
"keywords": [
"streamlit"
],
"author": "Streamlit",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/streamlit/streamlit/issues"
},
"homepage": "https://github.com/streamlit/streamlit#readme",
"dependencies": {
"apache-arrow": "^11.0.0",
"hoist-non-react-statics": "^3.3.2",
"react": "^16.14.0",
"react-dom": "^16.14.0"
},
"devDependencies": {
"@babel/preset-env": "^7.21.4",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.21.4",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "<13",
"@types/babel__preset-env": "~7.10.0",
"@types/hoist-non-react-statics": "^3.3.1",
"@types/jest": "^29.5.0",
"@types/node": "^12.0.0",
"@types/react": "^16.14.41",
"@types/react-dom": "^16.9.24",
"babel-jest": "^29.5.0",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"ts-node": "^10.9.1",
"typescript": "^5.0.4",
"typesync": "^0.14.3"
},
"resolutions": {
"@types/react": "^16.14.41",
"@types/react-dom": "^16.9.24"
},
"packageManager": "yarn@4.5.3"
}
| 767
|
streamlit
|
streamlit/component-lib/src/ArrowTable.test.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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 { ArrowTable } from "./ArrowTable";
import { EXAMPLE_DF } from "./mock_data";
const range = (startAt = 0, endAt = 0) =>
Array(endAt - startAt)
.fill(0)
.map((_, i) => i + startAt);
describe("ArrowTable", () => {
const table = new ArrowTable(
EXAMPLE_DF.data,
EXAMPLE_DF.index,
EXAMPLE_DF.columns
);
test("basic getters should returns values for basic table", () => {
expect(table.rows).toEqual(6);
expect(table.columns).toEqual(4);
expect(table.headerRows).toEqual(1);
expect(table.headerColumns).toEqual(1);
expect(table.dataRows).toEqual(5);
expect(table.dataColumns).toEqual(3);
expect(table.uuid).toEqual(undefined);
expect(table.caption).toEqual(undefined);
expect(table.styles).toEqual(undefined);
expect(table.table).toBeDefined();
expect(table.index).toBeDefined();
expect(table.columnTable).toBeDefined();
});
test.each([
{
rowIndex: 0,
columnIndex: 0,
expectedResult: {
classNames: "blank",
content: "",
type: "blank",
},
},
{
rowIndex: 0,
columnIndex: 1,
expectedResult: {
classNames: "col_heading level0 col0",
content: "First Name",
type: "columns",
},
},
{
rowIndex: 1,
columnIndex: 0,
expectedResult: {
classNames: "row_heading level0 row0",
content: BigInt(0),
id: "T_undefinedlevel0_row0",
type: "index",
},
},
{
rowIndex: 1,
columnIndex: 1,
expectedResult: {
classNames: "data row0 col0",
content: "Jason",
id: "T_undefinedrow0_col0",
type: "data",
},
},
{
rowIndex: 5,
columnIndex: 3,
expectedResult: {
classNames: "data row4 col2",
content: BigInt(73),
id: "T_undefinedrow4_col2",
type: "data",
},
},
])(
"getCell should return cell metadata",
({ rowIndex, columnIndex, expectedResult }) => {
expect(table.getCell(rowIndex, columnIndex)).toEqual(expectedResult);
}
);
test("getCell should return cell content", () => {
const celContents = range(0, table.rows).map((rowIndex) =>
range(0, table.columns).map(
(columnIndex) => table.getCell(rowIndex, columnIndex).content
)
);
expect(celContents).toEqual([
["", "First Name", "Last Name", "Age"],
[BigInt(0), "Jason", "Miller", BigInt(42)],
[BigInt(1), "Molly", "Jacobson", BigInt(52)],
[BigInt(2), "Tina", "Ali", BigInt(36)],
[BigInt(3), "Jake", "Milner", BigInt(24)],
[BigInt(4), "Amy", "Smith", BigInt(73)],
]);
});
test("serialize should returns Uint8Array", () => {
const { data, index, columns } = table.serialize();
expect(data).toBeInstanceOf(Uint8Array);
expect(index).toBeInstanceOf(Uint8Array);
expect(columns).toBeInstanceOf(Uint8Array);
const new_table = new ArrowTable(data, index, columns);
expect(new_table.rows).toEqual(6);
expect(new_table.columns).toEqual(4);
expect(new_table.headerRows).toEqual(1);
expect(new_table.headerColumns).toEqual(1);
});
});
| 1,591
|
streamlit
|
streamlit/component-lib/src/ArrowTable.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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 {
tableToIPC,
tableFromIPC,
Table,
Type,
Vector,
StructRow,
} from "apache-arrow";
export type CellType = "blank" | "index" | "columns" | "data";
/** Data types used by ArrowJS. */
export type DataType =
| null
| boolean
| number
| string
| Date // datetime
| Int32Array // int
| Uint8Array // bytes
| Vector // arrays
| StructRow; // interval
export interface ArrowDataframeProto {
data: ArrowTableProto;
height: string;
width: string;
}
export interface ArrowTableProto {
data: Uint8Array;
index: Uint8Array;
columns: Uint8Array;
styler?: Styler;
}
export interface Cell {
classNames: string;
content: DataType;
id?: string;
type: CellType;
}
export interface Styler {
caption?: string;
displayValuesTable: Table;
styles?: string;
uuid: string;
}
export class ArrowTable {
private readonly dataTable: Table;
private readonly indexTable: Table;
private readonly columnsTable: Table;
private readonly styler?: Styler;
constructor(
dataBuffer: Uint8Array,
indexBuffer: Uint8Array,
columnsBuffer: Uint8Array,
styler?: any
) {
this.dataTable = tableFromIPC(dataBuffer);
this.indexTable = tableFromIPC(indexBuffer);
this.columnsTable = tableFromIPC(columnsBuffer);
this.styler = styler
? {
caption: styler.caption,
displayValuesTable: tableFromIPC(styler.displayValues),
styles: styler.styles,
uuid: styler.uuid,
}
: undefined;
}
get rows(): number {
return this.indexTable.numRows + this.columnsTable.numCols;
}
get columns(): number {
return this.indexTable.numCols + this.columnsTable.numRows;
}
get headerRows(): number {
return this.rows - this.dataRows;
}
get headerColumns(): number {
return this.columns - this.dataColumns;
}
get dataRows(): number {
return this.dataTable.numRows;
}
get dataColumns(): number {
return this.dataTable.numCols;
}
get uuid(): string | undefined {
return this.styler && this.styler.uuid;
}
get caption(): string | undefined {
return this.styler && this.styler.caption;
}
get styles(): string | undefined {
return this.styler && this.styler.styles;
}
get table(): Table {
return this.dataTable;
}
get index(): Table {
return this.indexTable;
}
get columnTable(): Table {
return this.columnsTable;
}
public getCell = (rowIndex: number, columnIndex: number): Cell => {
const isBlankCell =
rowIndex < this.headerRows && columnIndex < this.headerColumns;
const isIndexCell =
rowIndex >= this.headerRows && columnIndex < this.headerColumns;
const isColumnsCell =
rowIndex < this.headerRows && columnIndex >= this.headerColumns;
if (isBlankCell) {
const classNames = ["blank"];
if (columnIndex > 0) {
classNames.push("level" + rowIndex);
}
return {
type: "blank",
classNames: classNames.join(" "),
content: "",
};
} else if (isColumnsCell) {
const dataColumnIndex = columnIndex - this.headerColumns;
const classNames = [
"col_heading",
"level" + rowIndex,
"col" + dataColumnIndex,
];
return {
type: "columns",
classNames: classNames.join(" "),
content: this.getContent(this.columnsTable, dataColumnIndex, rowIndex),
};
} else if (isIndexCell) {
const dataRowIndex = rowIndex - this.headerRows;
const classNames = [
"row_heading",
"level" + columnIndex,
"row" + dataRowIndex,
];
return {
type: "index",
id: `T_${this.uuid}level${columnIndex}_row${dataRowIndex}`,
classNames: classNames.join(" "),
content: this.getContent(this.indexTable, dataRowIndex, columnIndex),
};
} else {
const dataRowIndex = rowIndex - this.headerRows;
const dataColumnIndex = columnIndex - this.headerColumns;
const classNames = [
"data",
"row" + dataRowIndex,
"col" + dataColumnIndex,
];
const content = this.styler
? this.getContent(
this.styler.displayValuesTable,
dataRowIndex,
dataColumnIndex
)
: this.getContent(this.dataTable, dataRowIndex, dataColumnIndex);
return {
type: "data",
id: `T_${this.uuid}row${dataRowIndex}_col${dataColumnIndex}`,
classNames: classNames.join(" "),
content,
};
}
};
public getContent = (
table: Table,
rowIndex: number,
columnIndex: number
): DataType => {
const column = table.getChildAt(columnIndex);
if (column === null) {
return "";
}
const columnTypeId = this.getColumnTypeId(table, columnIndex);
switch (columnTypeId) {
case Type.Timestamp: {
return this.nanosToDate(column.get(rowIndex));
}
default: {
return column.get(rowIndex);
}
}
};
/**
* Serialize arrow table.
*/
public serialize(): ArrowTableProto {
return {
data: tableToIPC(this.dataTable),
index: tableToIPC(this.indexTable),
columns: tableToIPC(this.columnsTable),
};
}
/**
* Returns apache-arrow specific typeId of column.
*/
private getColumnTypeId(table: Table, columnIndex: number): Type {
return table.schema.fields[columnIndex].type.typeId;
}
private nanosToDate(nanos: number): Date {
return new Date(nanos / 1e6);
}
}
| 2,387
|
streamlit
|
streamlit/component-lib/src/StreamlitReact.test.tsx
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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 {
ComponentProps,
StreamlitComponentBase,
withStreamlitConnection,
} from "./StreamlitReact";
import * as React from "react";
import { render } from "@testing-library/react";
import { tick } from "./test_utils";
import { EXAMPLE_DF } from "./mock_data";
import { ArrowTable } from "./ArrowTable";
import { Streamlit } from "./streamlit";
class StaticComponent extends StreamlitComponentBase {
render() {
return <>Static component</>;
}
}
describe("StreamlitReact", () => {
test("the component should be empty initially", () => {
const StreamlitComponent = withStreamlitConnection(StaticComponent);
expect(document.body.innerHTML).toEqual("");
render(<StreamlitComponent />);
expect(document.body.innerHTML).toEqual("<div></div>");
});
test("the component should be visible after initialization", async () => {
const StreamlitComponent = withStreamlitConnection(StaticComponent);
expect(document.body.innerHTML).toEqual("");
const { getByText } = render(<StreamlitComponent />);
window.postMessage({ type: "streamlit:render", args: {} }, "*");
await tick();
expect(getByText("Static component")).toBeInTheDocument();
});
test("the component should receive arguments from the parent frame", async () => {
interface ComponentArgument {
firstArg: string;
}
class ComponentWithArguments extends StreamlitComponentBase<
{},
ComponentArgument
> {
render(): JSX.Element {
return <p>{this.props.args.firstArg}</p>;
}
}
const Component = withStreamlitConnection(ComponentWithArguments);
const { getByText } = render(<Component />);
window.postMessage(
{ type: "streamlit:render", args: { firstArg: "Argument text 123" } },
"*"
);
await tick();
expect(getByText("Argument text 123")).toBeInTheDocument();
});
test("the component should receive dataframe from the parent frame", async () => {
interface ComponentArgument {
firstArg: ArrowTable;
}
class DataframeComponent extends StreamlitComponentBase<ComponentArgument> {
render() {
const firstArg = this.props.args.firstArg;
const { content } = firstArg.getCell(1, 1);
return <>{String(content)}</>;
}
}
const Component = withStreamlitConnection(DataframeComponent);
const { getByText } = render(<Component />);
window.postMessage(
{
type: "streamlit:render",
args: {},
dfs: [
{
key: "firstArg",
value: {
data: {
data: EXAMPLE_DF.data,
index: EXAMPLE_DF.index,
columns: EXAMPLE_DF.columns,
},
},
},
],
},
"*"
);
await tick();
expect(getByText("Jason")).toBeInTheDocument();
});
test("the component error should be visible", async () => {
class BrokenComponent extends StreamlitComponentBase {
render(): React.ReactNode {
throw new Error("Error in component");
}
}
jest.spyOn(console, "error").mockImplementation(() => {});
const Component = withStreamlitConnection(BrokenComponent);
const { getByText } = render(<Component />);
window.postMessage(
{
type: "streamlit:render",
args: {},
},
"*"
);
await tick();
expect(getByText("Component Error")).toBeInTheDocument();
expect(getByText("Error in component")).toBeInTheDocument();
expect(jest.mocked(console.error).mock.calls).toHaveLength(2);
});
test("the component should update the frame height initially", async () => {
jest.spyOn(Streamlit, "setFrameHeight");
const Component = withStreamlitConnection(StaticComponent);
const { getByText } = render(<Component />);
window.postMessage(
{
type: "streamlit:render",
args: {},
},
"*"
);
await tick();
expect(jest.mocked(Streamlit.setFrameHeight).mock.calls).toHaveLength(1);
expect(getByText("Static component")).toBeInTheDocument();
});
test("the component should update the frame height after updating the arguments", async () => {
jest.spyOn(Streamlit, "setFrameHeight");
const Component = withStreamlitConnection(StaticComponent);
render(<Component />);
for (const value of [1, 2, 3]) {
window.postMessage(
{
type: "streamlit:render",
args: { value },
},
"*"
);
await tick();
}
expect(jest.mocked(Streamlit.setFrameHeight).mock.calls).toHaveLength(3);
});
});
| 1,944
|
streamlit
|
streamlit/component-lib/src/StreamlitReact.tsx
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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 hoistNonReactStatics from "hoist-non-react-statics";
import React, { ReactNode } from "react";
import { RenderData, Streamlit, Theme } from "./streamlit";
/**
* Props passed to custom Streamlit components.
*/
export interface ComponentProps<ArgType = any> {
/** Named dictionary of arguments passed from Python. */
args: ArgType;
/** The component's width. */
width: number;
/**
* True if the component should be disabled.
* All components get disabled while the app is being re-run,
* and become re-enabled when the re-run has finished.
*/
disabled: boolean;
/** Theme definition dictionary passed from the main client.*/
theme?: Theme;
}
/**
* Optional Streamlit React-based component base class.
*
* You are not required to extend this base class to create a Streamlit
* component. If you decide not to extend it, you should implement the
* `componentDidMount` and `componentDidUpdate` functions in your own class,
* so that your plugin properly resizes.
*/
export class StreamlitComponentBase<
S = {},
ArgType = any
> extends React.PureComponent<ComponentProps<ArgType>, S> {
public componentDidMount(): void {
// After we're rendered for the first time, tell Streamlit that our height
// has changed.
Streamlit.setFrameHeight();
}
public componentDidUpdate(): void {
// After we're updated, tell Streamlit that our height may have changed.
Streamlit.setFrameHeight();
}
}
/**
* Wrapper for React-based Streamlit components.
*
* Bootstraps the communication interface between Streamlit and the component.
*/
export function withStreamlitConnection<ArgType = any>(
WrappedComponent: React.ComponentType<ComponentProps>
): React.ComponentType {
interface WrapperProps {}
interface WrapperState {
renderData?: RenderData<ArgType>;
componentError?: Error;
}
class ComponentWrapper extends React.PureComponent<
WrapperProps,
WrapperState
> {
public constructor(props: WrapperProps) {
super(props);
this.state = {
renderData: undefined,
componentError: undefined,
};
}
/**
* Error boundary function. This will be called if our wrapped
* component throws an error. We store the caught error in our state,
* and display it in the next render().
*/
public static getDerivedStateFromError = (
error: Error
): Partial<WrapperState> => {
return { componentError: error };
};
public componentDidMount = (): void => {
// Set up event listeners, and signal to Streamlit that we're ready.
// We won't render the component until we receive the first RENDER_EVENT.
Streamlit.events.addEventListener(
Streamlit.RENDER_EVENT,
this.onRenderEvent as EventListener
);
Streamlit.setComponentReady();
};
public componentDidUpdate = (): void => {
// If our child threw an error, we display it in render(). In this
// case, the child won't be mounted and therefore won't call
// `setFrameHeight` on its own. We do it here so that the rendered
// error will be visible.
if (this.state.componentError != null) {
Streamlit.setFrameHeight();
}
};
public componentWillUnmount = (): void => {
Streamlit.events.removeEventListener(
Streamlit.RENDER_EVENT,
this.onRenderEvent as EventListener
);
};
/**
* Streamlit is telling this component to redraw.
* We save the render data in State, so that it can be passed to the
* component in our own render() function.
*/
private onRenderEvent = (
event: CustomEvent<RenderData<ArgType>>
): void => {
// Update our state with the newest render data
this.setState({ renderData: event.detail });
};
public render(): ReactNode {
// If our wrapped component threw an error, display it.
if (this.state.componentError != null) {
return (
<div>
<h1>Component Error</h1>
<span>{this.state.componentError.message}</span>
</div>
);
}
// Don't render until we've gotten our first RENDER_EVENT from Streamlit.
if (this.state.renderData == null) {
return null;
}
return (
<WrappedComponent
width={window.innerWidth}
disabled={this.state.renderData.disabled}
args={this.state.renderData.args}
theme={this.state.renderData.theme}
/>
);
}
}
return hoistNonReactStatics(ComponentWrapper, WrappedComponent);
}
| 1,754
|
streamlit
|
streamlit/component-lib/src/index.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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.
*/
// Workaround for type-only exports:
// https://stackoverflow.com/questions/53728230/cannot-re-export-a-type-when-using-the-isolatedmodules-with-ts-3-2-2
import { ComponentProps as ComponentProps_ } from "./StreamlitReact";
import { RenderData as RenderData_, Theme as Theme_ } from "./streamlit";
export {
StreamlitComponentBase,
withStreamlitConnection,
} from "./StreamlitReact";
export { ArrowTable } from "./ArrowTable";
export { Streamlit } from "./streamlit";
export type ComponentProps = ComponentProps_;
export type RenderData<ArgType = any> = RenderData_<ArgType>;
export type Theme = Theme_;
| 365
|
streamlit
|
streamlit/component-lib/src/streamlit.test.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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, Theme } from "./streamlit";
import { ArrowTable } from "./ArrowTable";
import { EXAMPLE_DF } from "./mock_data";
import { tick } from "./test_utils";
describe("Streamlit", () => {
test("setComponentReady register listeners only once", () => {
jest.spyOn(window, "addEventListener");
Streamlit.setComponentReady();
Streamlit.setComponentReady();
expect(jest.mocked(window.addEventListener).mock.calls).toHaveLength(1);
});
test("setComponentReady sends message to parent window", () => {
jest.spyOn(window.parent, "postMessage");
Streamlit.setComponentReady();
Streamlit.setComponentReady();
expect(jest.mocked(window.parent.postMessage).mock.calls).toEqual([
[
{
apiVersion: 1,
isStreamlitMessage: true,
type: "streamlit:componentReady",
},
"*",
],
[
{
apiVersion: 1,
isStreamlitMessage: true,
type: "streamlit:componentReady",
},
"*",
],
]);
});
test("setFrameHeight sends height to parent window", () => {
jest.spyOn(window.parent, "postMessage");
Object.defineProperty(document.body, "scrollHeight", {
value: 42,
configurable: true,
});
Streamlit.setFrameHeight();
expect(jest.mocked(window.parent.postMessage).mock.calls[0]).toEqual([
{
height: 42,
isStreamlitMessage: true,
type: "streamlit:setFrameHeight",
},
"*",
]);
// @ts-expect-error
delete document.body.scrollHeight;
});
test("setFrameHeight sends height to parent window only if changed", () => {
jest.spyOn(window.parent, "postMessage");
let scrollHeight = 42;
Object.defineProperty(document.body, "scrollHeight", {
get: () => scrollHeight,
configurable: true,
});
Streamlit.setFrameHeight();
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(1);
// Assert that the value is not sent again if height does not change
Streamlit.setFrameHeight();
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(1);
// Ensure that the NEW value is sent again
scrollHeight = 420;
Streamlit.setFrameHeight();
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(2);
expect(
jest.mocked(window.parent.postMessage).mock.calls[1][0].height
).toEqual(scrollHeight);
});
test("setComponentValue should support arrowTable", () => {
jest.spyOn(window.parent, "postMessage");
const table = new ArrowTable(
EXAMPLE_DF.data,
EXAMPLE_DF.index,
EXAMPLE_DF.columns
);
Streamlit.setComponentValue(table);
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(1);
const parentMessage = jest.mocked(window.parent.postMessage).mock
.calls[0][0];
// Assert content of message except value. The value is too complex for
// a simple assertion, so we will validate it separately
const value = parentMessage.value;
delete parentMessage.value;
expect(parentMessage).toEqual({
dataType: "dataframe",
isStreamlitMessage: true,
type: "streamlit:setComponentValue",
});
// Assert that the table has the expected characteristic.
const newTable = new ArrowTable(value.data, value.index, value.columns);
expect(newTable.rows).toEqual(6);
expect(newTable.columns).toEqual(4);
expect(newTable.headerRows).toEqual(1);
expect(newTable.headerColumns).toEqual(1);
});
test("setComponentValue should support JSON values", () => {
jest.spyOn(window.parent, "postMessage");
Streamlit.setComponentValue("123");
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(1);
expect(jest.mocked(window.parent.postMessage).mock.calls[0]).toEqual([
{
dataType: "json",
isStreamlitMessage: true,
type: "streamlit:setComponentValue",
value: "123",
},
"*",
]);
});
test("setComponentValue should support array buffers", () => {
jest.spyOn(window.parent, "postMessage");
const value = new Uint8Array([1, 2]).buffer;
Streamlit.setComponentValue(value);
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(1);
expect(jest.mocked(window.parent.postMessage).mock.calls[0]).toEqual([
{
dataType: "bytes",
isStreamlitMessage: true,
type: "streamlit:setComponentValue",
value: new Uint8Array([1, 2]),
},
"*",
]);
});
test("setComponentValue should support typed arrays", () => {
jest.spyOn(window.parent, "postMessage");
const value = new Uint8Array([1, 2]);
Streamlit.setComponentValue(value);
expect(jest.mocked(window.parent.postMessage).mock.calls).toHaveLength(1);
expect(jest.mocked(window.parent.postMessage).mock.calls[0]).toEqual([
{
dataType: "bytes",
isStreamlitMessage: true,
type: "streamlit:setComponentValue",
value: new Uint8Array([1, 2]),
},
"*",
]);
});
test("data from the parent frame is received and propagated as an event", async () => {
const streamlitEventsListener = jest.fn();
Streamlit.events.addEventListener(
"streamlit:render",
streamlitEventsListener
);
Streamlit.setComponentReady();
window.postMessage({ type: "streamlit:render", args: {} }, "*");
await tick();
expect(streamlitEventsListener.mock.calls).toHaveLength(1);
const renderEvent = streamlitEventsListener.mock.calls[0][0];
expect(renderEvent.detail).toEqual({
args: {},
disabled: false,
theme: undefined,
});
});
test("The parent frame can set the theme", async () => {
const streamlitEventsListener = jest.fn();
Streamlit.events.addEventListener(
"streamlit:render",
streamlitEventsListener
);
Streamlit.setComponentReady();
const theme: Theme = {
base: "red",
primaryColor: "blue",
backgroundColor: "green",
secondaryBackgroundColor: "purple",
textColor: "black",
font: "Courier New",
};
window.postMessage(
{ type: "streamlit:render", args: {}, theme: theme },
"*"
);
await tick();
expect(streamlitEventsListener.mock.calls).toHaveLength(1);
const renderEvent = streamlitEventsListener.mock.calls[0][0];
expect(renderEvent.detail.theme).toEqual(theme);
expect(
getComputedStyle(document.documentElement).getPropertyValue(
"--primary-color"
)
).toEqual(theme.primaryColor);
expect(
getComputedStyle(document.documentElement).getPropertyValue(
"--background-color"
)
).toEqual(theme.backgroundColor);
expect(
getComputedStyle(document.documentElement).getPropertyValue(
"--secondary-background-color"
)
).toEqual(theme.secondaryBackgroundColor);
expect(
getComputedStyle(document.documentElement).getPropertyValue(
"--text-color"
)
).toEqual(theme.textColor);
expect(
document.getElementById(Streamlit.INJECTED_STYLE_ELEMENT_ID)
).toBeInstanceOf(HTMLStyleElement);
expect(
document.querySelectorAll(`style#${Streamlit.INJECTED_STYLE_ELEMENT_ID}`)
).toHaveLength(1);
window.postMessage(
{ type: "streamlit:render", args: {}, theme: theme },
"*"
);
await tick();
expect(
document.querySelectorAll(`style#${Streamlit.INJECTED_STYLE_ELEMENT_ID}`)
).toHaveLength(1);
});
test("The parent frame can sent plain arguments", async () => {
const streamlitEventsListener = jest.fn();
Streamlit.events.addEventListener(
"streamlit:render",
streamlitEventsListener
);
Streamlit.setComponentReady();
window.postMessage(
{
type: "streamlit:render",
args: { textValue: "smile", numberValue: 42 },
},
"*"
);
await tick();
expect(streamlitEventsListener.mock.calls).toHaveLength(1);
const renderEvent = streamlitEventsListener.mock.calls[0][0];
expect(renderEvent.detail.args).toEqual({
numberValue: 42,
textValue: "smile",
});
});
test("The parent frame can sent dataframe", async () => {
const streamlitEventsListener = jest.fn();
Streamlit.events.addEventListener(
"streamlit:render",
streamlitEventsListener
);
Streamlit.setComponentReady();
window.postMessage(
{
type: "streamlit:render",
args: {},
dfs: [
{
key: "first-df",
value: {
data: {
data: EXAMPLE_DF.data,
index: EXAMPLE_DF.index,
columns: EXAMPLE_DF.columns,
},
},
},
],
},
"*"
);
await tick();
expect(streamlitEventsListener.mock.calls).toHaveLength(1);
const renderEvent = streamlitEventsListener.mock.calls[0][0];
const arrowTable = renderEvent.detail.args["first-df"];
expect(arrowTable.rows).toEqual(6);
expect(arrowTable.columns).toEqual(4);
expect(arrowTable.headerRows).toEqual(1);
expect(arrowTable.headerColumns).toEqual(1);
});
test("The parent frame can disable component", async () => {
const streamlitEventsListener = jest.fn();
Streamlit.events.addEventListener(
"streamlit:render",
streamlitEventsListener
);
Streamlit.setComponentReady();
window.postMessage(
{ type: "streamlit:render", args: {}, disabled: true },
"*"
);
await tick();
expect(streamlitEventsListener.mock.calls).toHaveLength(1);
const renderEvent = streamlitEventsListener.mock.calls[0][0];
expect(renderEvent.detail.disabled).toEqual(true);
});
});
| 4,132
|
streamlit
|
streamlit/component-lib/src/streamlit.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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.
*/
// Safari doesn't support the EventTarget class, so we use a shim.
import { ArrowDataframeProto, ArrowTable } from "./ArrowTable";
/** Object defining the currently set theme. */
export interface Theme {
base: string;
primaryColor: string;
backgroundColor: string;
secondaryBackgroundColor: string;
textColor: string;
font: string;
}
/** Data sent in the custom Streamlit render event. */
export interface RenderData<ArgType = any> {
args: ArgType;
disabled: boolean;
theme?: Theme;
}
// Types that Streamlit.setComponentValue accepts
type ComponentValue = ArrowTable | TypedArray | ArrayBuffer | any;
/** Messages from Component -> Streamlit */
enum ComponentMessageType {
// A component sends this message when it's ready to receive messages
// from Streamlit. Streamlit won't send any messages until it gets this.
// Data: { apiVersion: number }
COMPONENT_READY = "streamlit:componentReady",
// The component has a new widget value. Send it back to Streamlit, which
// will then re-run the app.
// Data: { value: any }
SET_COMPONENT_VALUE = "streamlit:setComponentValue",
// The component has a new height for its iframe.
// Data: { height: number }
SET_FRAME_HEIGHT = "streamlit:setFrameHeight",
}
/**
* Streamlit communication API.
*
* Components can send data to Streamlit via the functions defined here,
* and receive data from Streamlit via the `events` property.
*/
export class Streamlit {
/**
* The Streamlit component API version we're targeting.
* There's currently only 1!
*/
public static readonly API_VERSION = 1;
public static readonly RENDER_EVENT = "streamlit:render";
public static readonly INJECTED_STYLE_ELEMENT_ID =
"__streamlit_injected_styles";
/** Dispatches events received from Streamlit. */
public static readonly events = new EventTarget();
private static registeredMessageListener = false;
private static lastFrameHeight?: number;
/**
* Tell Streamlit that the component is ready to start receiving data.
* Streamlit will defer emitting RENDER events until it receives the
* COMPONENT_READY message.
*/
public static setComponentReady = (): void => {
if (!Streamlit.registeredMessageListener) {
// Register for message events if we haven't already
window.addEventListener("message", Streamlit.onMessageEvent);
Streamlit.registeredMessageListener = true;
}
Streamlit.sendBackMsg(ComponentMessageType.COMPONENT_READY, {
apiVersion: Streamlit.API_VERSION,
});
};
/**
* Report the component's height to Streamlit.
* This should be called every time the component changes its DOM - that is,
* when it's first loaded, and any time it updates.
*/
public static setFrameHeight = (height?: number): void => {
if (height === undefined) {
// `height` is optional. If undefined, it defaults to scrollHeight,
// which is the entire height of the element minus its border,
// scrollbar, and margin.
height = document.body.scrollHeight;
}
if (height === Streamlit.lastFrameHeight) {
// Don't bother updating if our height hasn't changed.
return;
}
Streamlit.lastFrameHeight = height;
Streamlit.sendBackMsg(ComponentMessageType.SET_FRAME_HEIGHT, { height });
};
/**
* Set the component's value. This value will be returned to the Python
* script, and the script will be re-run.
*
* For example:
*
* JavaScript:
* Streamlit.setComponentValue("ahoy!")
*
* Python:
* value = st.my_component(...)
* st.write(value) # -> "ahoy!"
*
* The value must be an ArrowTable, a typed array, an ArrayBuffer, or be
* serializable to JSON.
*/
public static setComponentValue = (value: ComponentValue): void => {
let dataType;
if (value instanceof ArrowTable) {
dataType = "dataframe";
value = value.serialize();
} else if (isTypedArray(value)) {
// All typed arrays get sent as Uint8Array, because that's what our
// protobuf library uses for the "bytes" field type.
dataType = "bytes";
value = new Uint8Array(value.buffer);
} else if (value instanceof ArrayBuffer) {
dataType = "bytes";
value = new Uint8Array(value);
} else {
dataType = "json";
}
Streamlit.sendBackMsg(ComponentMessageType.SET_COMPONENT_VALUE, {
value,
dataType,
});
};
/** Receive a ForwardMsg from the Streamlit app */
private static onMessageEvent = (event: MessageEvent): void => {
const type = event.data["type"];
switch (type) {
case Streamlit.RENDER_EVENT:
Streamlit.onRenderMessage(event.data);
break;
}
};
/**
* Handle an untyped Streamlit render event and redispatch it as a
* StreamlitRenderEvent.
*/
private static onRenderMessage = <ArgType = any>(data: {
args: ArgType;
dfs?: ArgsDataframe[];
disabled?: boolean;
theme?: Theme;
}): void => {
let args = data["args"];
if (args == null) {
console.error(
`Got null args in onRenderMessage. This should never happen`
);
args = {} as ArgType;
}
// Parse our dataframe arguments with arrow, and merge them into our args dict
const dataframeArgs =
data["dfs"] && data["dfs"].length > 0
? Streamlit.argsDataframeToObject(data["dfs"])
: {};
args = {
...args,
...dataframeArgs,
};
const disabled = Boolean(data["disabled"]);
const theme = data["theme"];
if (theme) {
_injectTheme(theme);
}
// Dispatch a render event!
const eventData = { disabled, args, theme };
const event = new CustomEvent<RenderData<ArgType>>(
Streamlit.RENDER_EVENT,
{
detail: eventData,
}
);
Streamlit.events.dispatchEvent(event);
};
private static argsDataframeToObject = (
argsDataframe: ArgsDataframe[]
): object => {
const argsDataframeArrow = argsDataframe.map(
({ key, value }: ArgsDataframe) => [key, Streamlit.toArrowTable(value)]
);
return Object.fromEntries(argsDataframeArrow);
};
private static toArrowTable = (df: ArrowDataframeProto): ArrowTable => {
const { data, index, columns, styler } = df.data;
return new ArrowTable(data, index, columns, styler);
};
/** Post a message to the Streamlit app. */
private static sendBackMsg = (type: string, data?: any): void => {
window.parent.postMessage(
{
isStreamlitMessage: true,
type: type,
...data,
},
"*"
);
};
}
const _injectTheme = (theme: Theme) => {
let style = document.getElementById(Streamlit.INJECTED_STYLE_ELEMENT_ID);
if (!style) {
style = document.createElement("style");
style.id = Streamlit.INJECTED_STYLE_ELEMENT_ID;
document.head.appendChild(style);
}
style.innerHTML = `
:root {
--primary-color: ${theme.primaryColor};
--background-color: ${theme.backgroundColor};
--secondary-background-color: ${theme.secondaryBackgroundColor};
--text-color: ${theme.textColor};
--font: ${theme.font};
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
`;
};
interface ArgsDataframe {
key: string;
value: ArrowDataframeProto;
}
// The TypedArray JavaScript types
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array;
/** True if the value is a TypedArray. */
function isTypedArray(value: any): value is TypedArray {
let isBigIntArray = false;
try {
isBigIntArray =
value instanceof BigInt64Array || value instanceof BigUint64Array;
} catch (e) {
// Ignore cause Safari does not support this
// https://caniuse.com/mdn-javascript_builtins_bigint64array
}
return (
value instanceof Int8Array ||
value instanceof Uint8Array ||
value instanceof Uint8ClampedArray ||
value instanceof Int16Array ||
value instanceof Uint16Array ||
value instanceof Int32Array ||
value instanceof Uint32Array ||
value instanceof Float32Array ||
value instanceof Float64Array ||
isBigIntArray
);
}
| 3,064
|
streamlit
|
streamlit/component-lib/src/test_utils.ts
|
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
*
* 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 function that doesn't do anything, but allows you to release
// handlers so that pending events can be executed.
//
// MDN explains this as well:
//
// postMessage() schedules the MessageEvent to be dispatched only after all pending execution
// contexts have finished. For example, if postMessage() is invoked in an event handler,
// that event handler will run to completion, as will any remaining handlers for that same
// event, before the MessageEvent is dispatched.
// Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
export const tick = () =>
new Promise((resolve) => setTimeout(() => resolve(0), 0));
| 334
|
streamlit
|
streamlit/component-lib/tsconfig.json
|
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"baseUrl": "src",
"declaration": true,
"declarationDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["dom", "dom.iterable", "esnext"],
"module": "esnext",
"moduleResolution": "node",
"outDir": "./dist",
"resolveJsonModule": true,
"strict": true,
"target": "es5"
},
"include": ["src"]
}
| 222
|
streamlit
|
streamlit/e2e_playwright/.coveragerc
|
[run]
omit =
*/streamlit/proto/*
*/streamlit/vendor/*
*/streamlit/static/*
[report]
omit =
*/streamlit/proto/*
*/streamlit/vendor/*
*/streamlit/static/*
exclude_also =
if TYPE_CHECKING:
def dg\(self\)
raise NotImplementedError
| 118
|
streamlit
|
streamlit/e2e_playwright/.streamlit/secrets.toml
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
[fake]
FAKE_SECRET="value"
| 183
|
streamlit
|
streamlit/e2e_playwright/CLAUDE.md
|
@./AGENTS.md
| 7
|
streamlit
|
streamlit/e2e_playwright/README.md
|
# Playwright e2e Tests
You can find documentation on how to use and implement Playwright end-to-end tests in [our wiki](../wiki/running-e2e-tests.md).
| 46
|
streamlit
|
streamlit/e2e_playwright/app_hotkeys_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 (
expect_prefixed_markdown,
)
def test_shows_clear_cache_dialog_when_c_is_pressed(app: Page):
app.keyboard.type("c")
expect(app.get_by_role("dialog")).to_be_visible()
expect(app.get_by_role("dialog")).to_contain_text("Clear caches")
modifier_keys = ["Control", "Meta"]
def test_does_not_show_clear_cache_when_modifier_c_is_pressed(app: Page):
for key in modifier_keys:
app.keyboard.press(f"{key}+c")
expect(app.get_by_test_id("stClearCacheDialog")).not_to_be_visible()
def test_does_not_clear_cache_dialog_when_c_is_pressed_inside_text_input(app: Page):
app.get_by_test_id("stTextInput").type("c")
expect(app.get_by_test_id("stClearCacheDialog")).not_to_be_visible()
def test_reruns_when_r_is_pressed(app: Page):
expect_prefixed_markdown(app, "Script runs:", "1", exact_match=False)
app.keyboard.type("r")
wait_for_app_run(app)
expect_prefixed_markdown(app, "Script runs:", "2", exact_match=False)
def test_does_not_rerun_when_r_is_pressed_inside_text_input(
app: Page,
):
app.get_by_test_id("stTextInput").locator("input").press("r")
wait_for_app_run(app)
expect_prefixed_markdown(app, "Script runs:", "1", exact_match=False)
| 725
|
streamlit
|
streamlit/e2e_playwright/appnode_hierarchy.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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",
],
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")
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()
| 785
|
streamlit
|
streamlit/e2e_playwright/appnode_hierarchy_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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")
| 1,458
|
streamlit
|
streamlit/e2e_playwright/auth_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING
import pytest
from playwright.sync_api import Page, expect
from e2e_playwright.conftest import (
AsyncSubprocess,
find_available_port,
wait_for_app_run,
)
from e2e_playwright.shared.app_utils import get_button, get_markdown
if TYPE_CHECKING:
from collections.abc import Generator
AUTH_SECRETS_TEMPLATE = """
[auth]
redirect_uri = "http://localhost:{app_port}/oauth2callback"
cookie_secret = "your_cookie_secret_here"
[auth.testprovider]
client_id = "test-client-id"
client_secret = "test-client-secret"
server_metadata_url = "http://localhost:{oidc_server_port}/.well-known/openid-configuration"
"""
@pytest.fixture(scope="module")
def oidc_server_port() -> int:
"""Fixture that returns the port of the OIDC server."""
return find_available_port()
@pytest.fixture(scope="module")
def fake_oidc_server(
request: pytest.FixtureRequest, oidc_server_port: int
) -> Generator[AsyncSubprocess, None, None]:
"""Fixture that starts and stops the OIDC app server."""
is_success = getattr(request, "param", "success")
oidc_server_proc = AsyncSubprocess(
[
"python",
"shared/oidc_mock_server.py",
"--port",
str(oidc_server_port),
"--success" if is_success == "success" else "--failure",
],
cwd=".",
)
oidc_server_proc.start()
time.sleep(1)
yield oidc_server_proc
oidc_server_stdout = oidc_server_proc.terminate()
print(oidc_server_stdout, flush=True)
@pytest.fixture(scope="module")
def prepare_secrets_file(app_port: int, oidc_server_port: int):
"""Fixture that inject the correct port to auth_secrets.toml file redirect_uri."""
# Read in the file
rendered_secrets = AUTH_SECRETS_TEMPLATE.format(
app_port=app_port, oidc_server_port=oidc_server_port
)
with NamedTemporaryFile(suffix=".toml", delete=False) as tmp_secrets_file:
tmp_secrets_file.write(rendered_secrets.encode())
tmp_secrets_file.flush()
yield tmp_secrets_file.name
@pytest.fixture(scope="module")
def app_server_extra_args(prepare_secrets_file: str) -> list[str]:
"""Fixture that returns extra arguments to pass to the Streamlit app server."""
return [
"--secrets.files",
prepare_secrets_file,
]
@pytest.mark.parametrize("fake_oidc_server", ["success"], indirect=True)
@pytest.mark.usefixtures("fake_oidc_server", "prepare_secrets_file")
def test_login_successful(app: Page):
"""Test authentication flow with test provider."""
button_element = get_button(app, "TEST LOGIN")
button_element.click()
app.wait_for_timeout(2_000)
text = get_markdown(app, "authtest@example.com")
expect(text).to_be_visible()
wait_for_app_run(app)
text = get_markdown(app, "John Doe")
expect(text).to_be_visible()
@pytest.mark.parametrize("fake_oidc_server", ["failure"], indirect=True)
@pytest.mark.usefixtures("fake_oidc_server", "prepare_secrets_file")
def test_login_failure(app: Page):
"""Test authentication flow with error response from oidc server."""
button_element = get_button(app, "TEST LOGIN")
button_element.click()
app.wait_for_timeout(2_000)
wait_for_app_run(app)
text = app.get_by_test_id("stMarkdownContainer").filter(has_text="John Doe")
expect(text).not_to_be_attached()
| 1,527
|
streamlit
|
streamlit/e2e_playwright/basic_app_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
import pytest
from playwright.sync_api import Page, Response, WebSocket, expect
from e2e_playwright.shared.app_utils import goto_app
def test_is_webdriver_set(app: Page):
"""Test that verifies that the window.navigator.webdriver is set to True
when running inside an end-to-end test.
This isn't great but it's the best way we came up with to double-check that
MetricsManager.isWebdriver() does what we want it to. We basically just
copy the contents of that function here for testing :( .
"""
content = app.evaluate("window.navigator.webdriver")
assert content, "window.navigator.webdriver is set to False"
def test_total_loaded_assets_size_under_threshold(page: Page, app_port: int):
"""Test that verifies the total size of loaded web assets is under a
configured threshold.
"""
# Define an acceptable threshold for total size of web assets loaded on the
# frontend (in MB) for a basic app run. While its important to keep the total
# size of web assets low, you can modify this threshold if it's really needed
# to add some new features. But make sure that its justified and intended.
TOTAL_ASSET_SIZE_THRESHOLD_MB: Final = 3.8 # noqa: N806
total_size_bytes = 0
def handle_response(response: Response):
nonlocal total_size_bytes
try:
# First try content-length header
content_length = response.headers.get("content-length")
if content_length:
total_size_bytes += int(content_length)
else:
# If that fails, read the body (expensive for large files)
body = response.body()
total_size_bytes += len(body)
except Exception as ex:
print(f"Error calculating size of web assets: {ex}")
# Register the response handler
page.on("response", handle_response)
goto_app(page, f"http://localhost:{app_port}/")
# Wait until all dependent resources are loaded:
page.wait_for_load_state()
# Wait until Hello world is visible:
expect(page.get_by_text("Hello world")).to_be_visible()
# Additional wait for lazy-loaded resources to load:
page.wait_for_timeout(1000)
# Convert to MB and assert it's under threshold
total_size_mb = total_size_bytes / (1024 * 1024)
assert total_size_mb < TOTAL_ASSET_SIZE_THRESHOLD_MB, (
f"Total web asset size loaded on the frontend ({total_size_mb:.2f}MB) for a "
f"basic app exceeds {TOTAL_ASSET_SIZE_THRESHOLD_MB}MB limit. "
"In case this is expected and justified, you can change the "
"threshold in the test."
)
def test_check_total_websocket_message_number_and_size(page: Page, app_port: int):
"""Test that verifies the number and total size of websocket messages
of the basic app is under a configured threshold.
"""
# Define an acceptable threshold for total websocket message size (in bytes)
# for a basic app run. While its important to keep the total websocket message
# size low, you can modify this threshold if it's really needed, justified,
# and expected
# BackMsg's; currently: ~70 bytes
TOTAL_WEBSOCKET_SENT_SIZE_THRESHOLD_BYTES: Final = 150 # noqa: N806
# Number of websocket messages sent
EXPECTED_WEBSOCKET_MESSAGES_SENT: Final = 1 # noqa: N806
# ForwardMsg's; currently: ~1200 bytes
TOTAL_WEBSOCKET_RECEIVED_SIZE_THRESHOLD_BYTES: Final = 2000 # noqa: N806
# Number of websocket messages received
EXPECTED_WEBSOCKET_MESSAGES_RECEIVED: Final = 8 # noqa: N806
total_websocket_sent_size_bytes = 0
total_websocket_received_size_bytes = 0
total_websocket_messages_sent = 0
total_websocket_messages_received = 0
def on_web_socket(ws: WebSocket) -> None:
print(f"WebSocket opened: {ws.url}")
def on_frame_sent(payload: str | bytes) -> None:
nonlocal total_websocket_sent_size_bytes
nonlocal total_websocket_messages_sent
if isinstance(payload, str):
payload = payload.encode("utf-8")
total_websocket_sent_size_bytes += len(payload)
total_websocket_messages_sent += 1
def on_frame_received(payload: str | bytes) -> None:
nonlocal total_websocket_received_size_bytes
nonlocal total_websocket_messages_received
if isinstance(payload, str):
payload = payload.encode("utf-8")
total_websocket_received_size_bytes += len(payload)
total_websocket_messages_received += 1
ws.on("framesent", on_frame_sent)
ws.on("framereceived", on_frame_received)
ws.on("close", lambda _: print("WebSocket closed"))
# Register websocket handler
page.on("websocket", on_web_socket)
goto_app(page, f"http://localhost:{app_port}/")
# Wait until all dependent resources are loaded:
page.wait_for_load_state()
# Wait until Hello world is visible:
expect(page.get_by_text("Hello world")).to_be_visible()
# Assert that the total number of websocket messages received and sent is equal
assert total_websocket_messages_received == EXPECTED_WEBSOCKET_MESSAGES_RECEIVED, (
f"Total number of websocket messages received by the frontend "
f"{total_websocket_messages_received} but expected to receive "
f"{EXPECTED_WEBSOCKET_MESSAGES_RECEIVED}. In case this is expected, "
"you can change the number in the test."
)
assert total_websocket_messages_sent == EXPECTED_WEBSOCKET_MESSAGES_SENT, (
f"Total number of websocket messages sent by the frontend "
f"{total_websocket_messages_sent} but expected to send "
f"{EXPECTED_WEBSOCKET_MESSAGES_SENT}. In case this is expected, "
"you can change the number in the test."
)
# Assert that the total size of websocket messages is under the threshold:
assert (
total_websocket_received_size_bytes
< TOTAL_WEBSOCKET_RECEIVED_SIZE_THRESHOLD_BYTES
), (
f"Total received size of websocket messages "
f"({total_websocket_received_size_bytes} bytes) "
"exceeds the configured threshold "
f"({TOTAL_WEBSOCKET_RECEIVED_SIZE_THRESHOLD_BYTES} bytes)"
"In case this is expected and justified, you can change the "
"threshold in the test."
)
assert (
total_websocket_sent_size_bytes < TOTAL_WEBSOCKET_SENT_SIZE_THRESHOLD_BYTES
), (
"Total sent size of websocket messages "
f"({total_websocket_sent_size_bytes} bytes) "
"exceeds the configured threshold "
f"({TOTAL_WEBSOCKET_SENT_SIZE_THRESHOLD_BYTES} bytes)"
"In case this is expected and justified, you can change the "
"threshold in the test."
)
@pytest.mark.performance
def test_basic_app_performance(app: Page):
"""Collect performance metrics for a basic app."""
# Wait until all dependent resources are loaded:
app.wait_for_load_state()
expect(app.get_by_text("Hello world")).to_be_visible()
| 2,894
|
streamlit
|
streamlit/e2e_playwright/bidi_components/basics.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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")
# ---------------------------------------------------------------------------
# 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(
isolate_styles=True,
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(
isolate_styles=True,
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(
isolate_styles=True,
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(
isolate_styles=True,
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("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",
},
)
| 7,039
|
streamlit
|
streamlit/e2e_playwright/bidi_components/basics_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
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_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")).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")).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")).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")).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")).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")).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")).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_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()
| 3,917
|
streamlit
|
streamlit/e2e_playwright/bidi_components/error_handling.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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()
| 522
|
streamlit
|
streamlit/e2e_playwright/bidi_components/session_state_interactions.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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)
| 854
|
streamlit
|
streamlit/e2e_playwright/bidi_components/session_state_interactions_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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)
| 721
|
streamlit
|
streamlit/e2e_playwright/compilation_error_dialog_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
def test_compilation_error_dialog(
page: Page, app_port: int, assert_snapshot: ImageCompareFunction
):
# Do the navigation manually because our app fixture waits for the app to run, but
# with the compilation error the app never runs
page.goto(f"http://localhost:{app_port}/")
dialog = page.get_by_role("dialog")
expect(dialog).to_be_visible(timeout=10000)
# make sure that the close-x button is not focused
dialog.blur(timeout=0)
assert_snapshot(dialog, name="compilation_error-dialog")
| 378
|
streamlit
|
streamlit/e2e_playwright/config/script_level_config_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 re
from playwright.sync_api import Page, expect
from e2e_playwright.shared.app_utils import get_markdown
def test_secret_value_display_and_styling(app: Page):
"""Test that the script-level config and secrets are loaded correctly."""
secret_element = get_markdown(app, "Secret value: fake")
# Check the secrets value:
expect(secret_element).to_be_visible()
# Check that its using the monospace font family (theme.font=monospace):
# This needs to be a regex because the actual font-family can be a list of fonts.
expect(secret_element).to_have_css("font-family", re.compile(r".*monospace.*"))
# Check that the app is in dark mode (theme.base=dark):
app_container = app.get_by_test_id("stApp")
expect(app_container).to_have_css("color-scheme", "dark")
# Check that the main menu is not visible (toolbarMode=minimal):
expect(app.get_by_test_id("stMainMenu")).not_to_be_attached()
| 486
|
streamlit
|
streamlit/e2e_playwright/config_static_serving_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.shared.app_utils import (
get_markdown,
wait_for_all_images_to_be_loaded,
)
def test_should_serve_existing_asset(app: Page, app_port: int):
"""Test that the static serving feature serves an existing asset."""
response = app.request.get(
f"http://localhost:{app_port}/app/static/streamlit-logo.png"
)
expect(response).to_be_ok()
# Assert is safe here since we don't need to wait for something here:
assert response.status == 200
def test_should_return_error_on_non_existing_asset(app: Page, app_port: int):
"""Test that the static serving feature returns error code for non-existing asset."""
response = app.request.get(
f"http://localhost:{app_port}/app/static/notexisting.jpeg"
)
expect(response).not_to_be_ok()
# Assert is safe here since we don't need to wait for something here:
assert response.status == 404
def test_static_served_image_embedded_in_markdown(app: Page):
"""Test that an image served via the static serving can be embedded into markdown."""
markdown_element = get_markdown(app, "Images served via static serving:")
image_element = markdown_element.locator("img")
expect(image_element).to_be_visible()
wait_for_all_images_to_be_loaded(app)
| 630
|
streamlit
|
streamlit/e2e_playwright/conftest.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.
"""
Global pytest fixtures for e2e tests.
This file is automatically run by pytest before tests are executed.
"""
from __future__ import annotations
import hashlib
import os
import re
import shlex
import shutil
import socket
import subprocess
import sys
import time
from dataclasses import dataclass
from io import BytesIO, TextIOWrapper
from pathlib import Path
from random import randint
from tempfile import TemporaryFile
from typing import TYPE_CHECKING, Any, Literal, Protocol
from urllib import parse
import pytest
import requests
from PIL import Image
from playwright.sync_api import (
ElementHandle,
FrameLocator,
Locator,
Page,
Response,
Route,
expect,
)
from typing_extensions import Self
from e2e_playwright.shared.git_utils import get_git_root
from e2e_playwright.shared.performance import (
is_supported_browser,
measure_performance,
start_capture_traces,
)
if TYPE_CHECKING:
from collections.abc import Callable, Generator
from types import ModuleType, TracebackType
# Used for static app testing
class StaticPage(Page):
pass
def pytest_configure(config: pytest.Config) -> None:
"""Register custom markers."""
config.addinivalue_line(
"markers", "no_perf: mark test to not use performance profiling"
)
config.addinivalue_line(
"markers", "app_hash(hash): mark test to open the app with a URL hash"
)
def reorder_early_fixtures(metafunc: pytest.Metafunc) -> None:
"""Put fixtures with `pytest.mark.early` first during execution.
This allows patch of configurations before the application is initialized
Copied from: https://github.com/pytest-dev/pytest/issues/1216#issuecomment-456109892
"""
for fixture_definitions in metafunc._arg2fixturedefs.values():
fixturedef = fixture_definitions[0]
for mark in getattr(fixturedef.func, "pytestmark", []):
if mark.name == "early":
order = metafunc.fixturenames
order.insert(0, order.pop(order.index(fixturedef.argname)))
break
def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
reorder_early_fixtures(metafunc)
class AsyncSubprocess:
"""A context manager. Wraps subprocess. Popen to capture output safely."""
args: list[str]
cwd: str
env: dict[str, str]
_proc: subprocess.Popen[str] | None
_stdout_file: TextIOWrapper | None
def __init__(self, args: list[str], cwd: str, env: dict[str, str] | None = None):
self.args = args
self.cwd = cwd
self.env = env or {}
self._proc = None
self._stdout_file = None
def terminate(self) -> str | None:
"""Terminate the process and return its stdout/stderr in a string."""
if self._proc is not None:
self._proc.terminate()
self._proc.wait()
self._proc = None
# Read the stdout file and close it
stdout = None
if self._stdout_file is not None:
self._stdout_file.seek(0)
stdout = self._stdout_file.read()
self._stdout_file.close()
self._stdout_file = None
return stdout
def __enter__(self) -> Self:
self.start()
return self
def start(self) -> None:
# Start the process and capture its stdout/stderr output to a temp
# file. We do this instead of using subprocess.PIPE (which causes the
# Popen object to capture the output to its own internal buffer),
# because large amounts of output can cause it to deadlock.
self._stdout_file = TemporaryFile("w+")
print(f"Running: {shlex.join(self.args)}")
self._proc = subprocess.Popen(
self.args,
cwd=self.cwd,
stdout=self._stdout_file,
stderr=subprocess.STDOUT,
text=True,
env={**os.environ.copy(), **self.env},
)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self._proc is not None:
self._proc.terminate()
self._proc = None
if self._stdout_file is not None:
self._stdout_file.close()
self._stdout_file = None
def resolve_test_to_script(test_module: ModuleType) -> str:
"""Resolve the test module to the corresponding test script filename."""
assert test_module.__file__ is not None
return test_module.__file__.replace("_test.py", ".py")
def hash_to_range(
text: str,
min: int = 10000,
max: int = 65535,
) -> int:
sha256_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
return min + (int(sha256_hash, 16) % (max - min + 1))
def is_port_available(port: int, host: str) -> bool:
"""Check if a port is available on the given host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
return sock.connect_ex((host, port)) != 0
def find_available_port(
min_port: int = 10000,
max_port: int = 65535,
max_tries: int = 50,
host: str = "localhost",
) -> int:
"""Find an available port on the given host."""
for _ in range(max_tries):
selected_port = randint(min_port, max_port)
if is_port_available(selected_port, host):
return selected_port
raise RuntimeError("Unable to find an available port.")
def is_app_server_running(port: int, host: str = "localhost") -> bool:
"""Check if the app server is running."""
try:
return (
requests.get(f"http://{host}:{port}/_stcore/health", timeout=1).text == "ok"
)
except Exception:
return False
def wait_for_app_server_to_start(port: int, timeout: int = 5) -> bool:
"""Wait for the app server to start.
Parameters
----------
port : int
The port on which the app server is running.
timeout : int
The number of minutes to wait for the app server to start.
Returns
-------
bool
True if the app server is started, False otherwise.
"""
print(f"Waiting for app to start... {port}")
start_time = time.time()
while not is_app_server_running(port):
time.sleep(3)
if time.time() - start_time > 60 * timeout:
return False
return True
# region Fixtures
@pytest.fixture(scope="module")
def app_port(worker_id: str) -> int:
"""Fixture that returns an available port on localhost."""
if worker_id and worker_id != "master":
# This is run with xdist, we try to get a port by hashing the worker ID
port = hash_to_range(worker_id)
if is_port_available(port, "localhost"):
return port
# Find a random available port:
return find_available_port()
@pytest.fixture(scope="module")
def app_server_extra_args() -> list[str]:
"""Fixture that returns extra arguments to pass to the Streamlit app server."""
return []
@pytest.fixture(scope="module", autouse=True)
def app_server(
app_port: int,
app_server_extra_args: list[str],
request: pytest.FixtureRequest,
) -> Generator[AsyncSubprocess, None, None]:
"""Fixture that starts and stops the Streamlit app server."""
streamlit_proc = start_app_server(
app_port,
request.module,
extra_args=app_server_extra_args,
)
yield streamlit_proc
streamlit_stdout = streamlit_proc.terminate()
print(streamlit_stdout, flush=True)
@pytest.fixture
def app(page: Page, app_port: int, request: pytest.FixtureRequest) -> Page:
"""Fixture that opens the app."""
marker = request.node.get_closest_marker("app_hash")
hash_fragment = ""
if marker:
hash_fragment = f"#{marker.args[0]}"
response: Response | None = None
try:
response = page.goto(f"http://localhost:{app_port}/{hash_fragment}")
except Exception as e:
print(e, flush=True)
if response is None:
raise RuntimeError("Unable to load page")
if response.status != 200:
print(f"Unsuccessful in loading page. Status: {response.status}", flush=True)
if response.status == 404:
print(
"404 error: try building the frontend with make frontend-fast",
flush=True,
)
raise RuntimeError("Unable to load page")
print("Successfully loaded page", flush=True)
start_capture_traces(page)
wait_for_app_loaded(page)
return page
@pytest.fixture
def static_app(
page: Page,
app_port: int,
request: pytest.FixtureRequest,
) -> Page:
"""Fixture that opens the app."""
query_param = request.node.get_closest_marker("query_param")
query_string = query_param.args[0] if query_param else ""
# Indicate this is a StaticPage
page.__class__ = StaticPage
page.goto(f"http://localhost:{app_port}/{query_string}")
start_capture_traces(page)
wait_for_app_loaded(page)
return page
@pytest.fixture
def app_with_query_params(
page: Page, app_port: int, request: pytest.FixtureRequest
) -> tuple[Page, dict[str, Any]]:
"""Fixture that opens the app with additional query parameters.
The query parameters are passed as a dictionary in the 'param' key of the request.
"""
query_params = request.param
query_string = parse.urlencode(query_params, doseq=True)
url = f"http://localhost:{app_port}/?{query_string}"
page.goto(url)
wait_for_app_loaded(page)
return page, query_params
@dataclass
class IframedPageAttrs:
# id attribute added to the iframe html tag
element_id: str | None = None
# query params to be appended to the iframe src URL
src_query_params: dict[str, str] | None = None
# additional HTML body
additional_html_head: str | None = None
# html content to load. Following placeholders are replaced during the test:
# - $APP_URL: the URL of the Streamlit app
html_content: str | None = None
@dataclass
class IframedPage:
# the page to configure
page: Page
# opens the configured page via the iframe URL and returns the frame_locator
# pointing to the iframe
open_app: Callable[[IframedPageAttrs | None], FrameLocator]
@pytest.fixture
def iframed_app(page: Page, app_port: int) -> IframedPage:
"""Fixture that returns an IframedPage.
The page object can be used to configure additional routes, for example to override
the host-config. The open_app function triggers the opening of the app in an iframe.
"""
# we are going to intercept the request, so the address and html-file is arbitrarily
# chosen and does not even exist
fake_iframe_server_origin = "http://localhost:1345"
fake_iframe_server_route = f"{fake_iframe_server_origin}/iframed_app.html"
# the url where the Streamlit server is reachable
app_url = f"http://localhost:{app_port}"
# the CSP header returned for the Streamlit index.html loaded in the iframe. This is
# similar to a common CSP we have seen in the wild.
app_csp_header = f"""
default-src 'none';
worker-src blob:;
form-action 'none';
frame-ancestors {fake_iframe_server_origin};
frame-src data: {app_url}/_stcore/component/ {app_url}/component/;
img-src 'self' https: data: blob:;
media-src 'self' https: data: blob:;
connect-src ws://localhost:{app_port}/_stcore/stream
{app_url}/_stcore/component/
{app_url}/_stcore/bidi-components/
{app_url}/component/
{app_url}/_stcore/upload_file/
{app_url}/_stcore/host-config
{app_url}/_stcore/health
{app_url}/_stcore/message
{app_url}/media/
https://some-prefix.com/somethingelse/_stcore/upload_file/
https://events.mapbox.com/
https://api.mapbox.com/v4/
https://api.mapbox.com/raster/v1/
https://api.mapbox.com/rasterarrays/v1/
https://api.mapbox.com/styles/v1/mapbox/
https://api.mapbox.com/fonts/v1/mapbox/
https://api.mapbox.com/models/v1/mapbox/
https://api.mapbox.com/map-sessions/v1
https://data.streamlit.io/tokens.json
https://basemaps.cartocdn.com
https://tiles.basemaps.cartocdn.com
https://tiles-a.basemaps.cartocdn.com
https://tiles-b.basemaps.cartocdn.com
https://tiles-c.basemaps.cartocdn.com
https://tiles-d.basemaps.cartocdn.com
data: blob:;
style-src 'unsafe-inline'
https://api.mapbox.com/mapbox-gl-js/
{app_url}/static/css/
blob:;
script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:
https://api.mapbox.com/mapbox-gl-js/
{app_url}/static/js/;
font-src {app_url}/static/fonts/ {app_url}/static/media/ https: data: blob:;
""".replace("\n", " ").strip()
def _open_app(iframe_element_attrs: IframedPageAttrs | None = None) -> FrameLocator:
_iframe_element_attrs = iframe_element_attrs
if _iframe_element_attrs is None:
_iframe_element_attrs = IframedPageAttrs()
query_params = ""
if _iframe_element_attrs.src_query_params:
query_params = "?" + parse.urlencode(_iframe_element_attrs.src_query_params)
src = f"{app_url}/{query_params}"
additional_html_head = (
_iframe_element_attrs.additional_html_head
if _iframe_element_attrs.additional_html_head
else ""
)
_iframed_body = (
f"""
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<meta charset="UTF-8">
<title>Iframed Streamlit App</title>
{additional_html_head}
</head>
<body style="height: 100%;">
<iframe
src={src}
id={
_iframe_element_attrs.element_id
if _iframe_element_attrs.element_id
else ""
}
title="Iframed Streamlit App"
allow="clipboard-read; clipboard-write; microphone; camera;"
sandbox="allow-modals allow-popups allow-same-origin allow-scripts allow-downloads"
width="100%"
>
</iframe>
</body>
</html>
"""
if _iframe_element_attrs.html_content is None
else _iframe_element_attrs.html_content.replace("$APP_URL", app_url)
)
def fulfill_iframe_request(route: Route) -> None:
"""Return as response an iframe that loads the actual Streamlit app."""
browser = page.context.browser
# webkit requires the iframe's parent to have "blob:" set, for example if we
# want to download a CSV via the blob: url; Chrome seems to be more lax
frame_src_blob = ""
if browser is not None and (
browser.browser_type.name in {"webkit", "firefox"}
):
frame_src_blob = "blob:"
route.fulfill(
status=200,
body=_iframed_body,
headers={
"Content-Type": "text/html",
"Content-Security-Policy": f"frame-src {frame_src_blob} {app_url};",
},
)
# intercept all requests to the fake iframe server and fulfill the request in
# playwright
page.route(fake_iframe_server_route, fulfill_iframe_request)
def fullfill_streamlit_app_request(route: Route) -> None:
"""Get the actual Streamlit app and return it's content."""
response = route.fetch()
route.fulfill(
body=response.body(),
headers={**response.headers, "Content-Security-Policy": app_csp_header},
)
# this will route the request to the actual Streamlit app
page.route(src, fullfill_streamlit_app_request)
def _expect_streamlit_app_loaded_in_iframe_with_added_header(
response: Response,
) -> bool:
"""Ensure that the routing-interception worked and that Streamlit app is
indeed loaded with the CSP header we expect.
"""
return (
response.url == src
and response.headers["content-security-policy"] == app_csp_header
)
with page.expect_event(
"response",
predicate=_expect_streamlit_app_loaded_in_iframe_with_added_header,
):
page.goto(fake_iframe_server_route, wait_until="domcontentloaded")
frame_locator = page.frame_locator("iframe")
frame_locator.nth(0).get_by_test_id("stAppViewContainer").wait_for(
timeout=30000, state="attached"
)
return frame_locator
return IframedPage(page, _open_app)
@pytest.fixture(scope="session")
def browser_type_launch_args(
browser_type_launch_args: dict[str, Any], browser_name: str
) -> dict[str, Any]:
"""Fixture that adds the fake device and ui args to the browser type launch args."""
# The browser context fixture in pytest-playwright is defined in session scope, and
# depends on the browser_type_launch_args fixture. This means that we can't
# redefine the browser_type_launch_args fixture more narrow scope
# e.g. function or module scope.
# https://github.com/microsoft/playwright-pytest/blob/ef99541352b307411dbc15c627e50f95de30cc71/pytest_playwright/pytest_playwright.py#L128
# We need to extend browser launch args to support fake video stream for
# st.camera_input test.
# https://github.com/microsoft/playwright/issues/4532#issuecomment-1491761713
if browser_name == "chromium":
browser_type_launch_args = {
**browser_type_launch_args,
"args": [
"--use-fake-device-for-media-stream",
"--use-fake-ui-for-media-stream",
],
}
elif browser_name == "firefox":
browser_type_launch_args = {
**browser_type_launch_args,
"firefox_user_prefs": {
"media.navigator.streams.fake": True,
"media.navigator.permission.disabled": True,
"permissions.default.microphone": 1,
"permissions.default.camera": 1,
# Reduces screenshot flakiness caused by subpixel rendering and
# font rendering:
"layout.css.devPixelsPerPx": "1.0",
"browser.display.use_system_colors": False,
"gfx.font_rendering.cleartype_params.rendering_mode": 5,
},
}
return browser_type_launch_args
@pytest.fixture(scope="session")
def browser_context_args(
browser_context_args: dict[str, Any], browser_name: str
) -> dict[str, Any]:
"""Fixture that adds clipboard permissions to the browser context for Chromium."""
# Clipboard permissions are only supported in Chromium-based browsers
if browser_name == "chromium":
return {
**browser_context_args,
"permissions": ["clipboard-read", "clipboard-write"],
}
return browser_context_args
@pytest.fixture(params=["light_theme", "dark_theme"])
def app_theme(request: pytest.FixtureRequest) -> str:
"""Fixture that returns the theme name."""
return str(request.param)
@pytest.fixture
def themed_app(page: Page, app_port: int, app_theme: str) -> Page:
"""Fixture that opens the app with the given theme."""
page.goto(f"http://localhost:{app_port}/?embed_options={app_theme}")
start_capture_traces(page)
wait_for_app_loaded(page)
return page
@pytest.fixture
def app_with_microphone_permission_denied(page: Page, app_port: int) -> Page:
"""Fixture that opens the app with getUserMedia mocked to deny microphone permissions.
This fixture is used for testing microphone permission denied error handling in audio
components. It injects a script that overrides navigator.mediaDevices.getUserMedia
to always reject with a NotAllowedError before the app loads.
"""
# Add init script BEFORE navigating to the page
page.add_init_script("""
// Override getUserMedia to always reject with NotAllowedError
// Must use DOMException to match browser behavior
Object.defineProperty(navigator.mediaDevices, 'getUserMedia', {
writable: false,
configurable: true,
value: async function() {
const error = new DOMException(
'Permission denied',
'NotAllowedError'
);
throw error;
}
});
""")
# Now navigate to the app
page.goto(f"http://localhost:{app_port}/")
wait_for_app_loaded(page)
return page
class ImageCompareFunction(Protocol):
def __call__(
self,
element: ElementHandle | Locator | Page,
*,
image_threshold: float = 0.002,
pixel_threshold: float = 0.05,
name: str | None = None,
fail_fast: bool = False,
style: str | None = None,
) -> None:
"""Compare a screenshot with screenshot from a past run.
Parameters
----------
element : ElementHandle or Locator
The element to take a screenshot of.
image_threshold : float, optional
The allowed percentage of different pixels in the image.
pixel_threshold : float, optional
The allowed percentage of difference for a single pixel.
name : str | None, optional
The name of the screenshot without an extension. If not provided, the name
of the test function will be used.
fail_fast : bool, optional
If True, the comparison will stop at the first pixel mismatch.
"""
@pytest.fixture(scope="session", autouse=True)
def delete_output_dir(pytestconfig: Any) -> None:
# Overwriting the default delete_output_dir fixture from pytest-playwright:
# There seems to be a bug with the combination of pytest-playwright, xdist,
# and pytest-rerunfailures where the output dir is deleted when it shouldn't be.
# To prevent this issue, we are not deleting the output dir when running with
# reruns and xdist.
uses_xdist = (
pytestconfig.getoption("workerinput", None) or os.getenv("PYTEST_XDIST_WORKER"),
)
uses_reruns = pytestconfig.getoption("reruns", None)
if not (uses_xdist and uses_reruns):
# Delete the output folder. Uses the same logic as the default
# delete_output_dir fixture from pytest-playwright:
# https://github.com/microsoft/playwright-pytest/blob/fb51327390ccbd3561c1777499934eb88296f1bf/pytest-playwright/pytest_playwright/pytest_playwright.py#L68
output_dir = pytestconfig.getoption("--output")
if os.path.exists(output_dir):
try:
shutil.rmtree(output_dir)
except FileNotFoundError:
# When running in parallel, another thread may have already deleted the
# files
pass
except OSError as error:
if error.errno != 16:
raise
# We failed to remove folder, might be due to the whole folder being
# mounted inside a container:
# https://github.com/microsoft/playwright/issues/12106
# https://github.com/microsoft/playwright-python/issues/1781
# Do a best-effort to remove all files inside of it instead.
entries = os.listdir(output_dir)
for entry in entries:
shutil.rmtree(entry)
@pytest.fixture(scope="session")
def output_folder(pytestconfig: Any) -> Path:
"""Fixture returning the directory that is used for all test failures information.
This includes:
- snapshot-tests-failures: This directory contains all the snapshots that did not
match with the snapshots from past runs. The folder structure is based on the folder
structure used in the main snapshots folder.
- snapshot-updates: This directory contains all the snapshots that got updated in
the current run based on folder structure used in the main snapshots folder.
"""
return Path(
get_git_root() / "e2e_playwright" / pytestconfig.getoption("--output")
).resolve()
@pytest.fixture
def assert_snapshot(
request: pytest.FixtureRequest,
output_folder: Path,
pytestconfig: Any,
) -> Generator[ImageCompareFunction, None, None]:
"""Fixture that compares a screenshot with screenshot from a past run."""
# Check if reruns are enabled for this test run
flaky_marker = request.node.get_closest_marker("flaky")
if flaky_marker and "reruns" in flaky_marker.kwargs:
configured_reruns = flaky_marker.kwargs["reruns"]
else:
configured_reruns = pytestconfig.getoption("reruns", 0)
# Get the current execution count:
execution_count = getattr(request.node, "execution_count", 1)
# True if this is the last rerun (or the only test run)
is_last_rerun = execution_count - 1 == configured_reruns
root_path = get_git_root()
platform = str(sys.platform)
module_name = request.module.__name__.split(".")[-1]
test_function_name = request.node.originalname
snapshot_dir: Path = (
root_path / "e2e_playwright" / "__snapshots__" / platform / module_name
)
module_snapshot_failures_dir: Path = (
output_folder / "snapshot-tests-failures" / platform / module_name
)
module_snapshot_updates_dir: Path = (
output_folder / "snapshot-updates" / platform / module_name
)
snapshot_file_suffix = ""
# Extract the parameter ids if they exist
match = re.search(r"\[(.*?)\]", request.node.name)
if match:
snapshot_file_suffix = f"[{match.group(1)}]"
snapshot_default_file_name: str = test_function_name + snapshot_file_suffix
test_failure_messages: list[str] = []
def compare(
element: ElementHandle | Locator | Page,
*,
image_threshold: float = 0.002,
pixel_threshold: float = 0.05,
name: str | None = None,
fail_fast: bool = False,
file_type: Literal["png", "jpg"] = "png",
style: str | None = None,
show_app_header: bool | None = None,
) -> None:
"""Compare a screenshot with screenshot from a past run.
Parameters
----------
element : ElementHandle or Locator
The element to take a screenshot of.
image_threshold : float, optional
The allowed percentage of different pixels in the image.
pixel_threshold : float, optional
The allowed percentage of difference for a single pixel to be considered
different.
name : str | None, optional
The name of the screenshot without an extension. If not provided, the name
of the test function will be used.
fail_fast : bool, optional
If True, the comparison will stop at the first pixel mismatch.
file_type: "png" or "jpg"
The file type of the screenshot. Defaults to "png".
show_app_header : bool or None
Whether to make the app header background transparent before taking the screenshot.
If None (default), the app header will be shown based on the
element type (page will always show the app header, other elements will hide it).
"""
nonlocal test_failure_messages
nonlocal snapshot_default_file_name
nonlocal module_snapshot_updates_dir
nonlocal module_snapshot_failures_dir
nonlocal snapshot_file_suffix
if show_app_header is False or (
show_app_header is None and not isinstance(element, Page)
):
# Make the app header background transparent:
if style is None:
style = ""
style += " .stAppHeader { background: transparent; }"
if file_type == "jpg":
file_extension = ".jpg"
img_bytes = element.screenshot(
type="jpeg", quality=90, animations="disabled", style=style
)
else:
file_extension = ".png"
img_bytes = element.screenshot(
type="png", animations="disabled", style=style
)
snapshot_file_name: str = snapshot_default_file_name
if name:
snapshot_file_name = name + snapshot_file_suffix
snapshot_file_path: Path = (
snapshot_dir / f"{snapshot_file_name}{file_extension}"
)
snapshot_updates_file_path: Path = (
module_snapshot_updates_dir / f"{snapshot_file_name}{file_extension}"
)
snapshot_file_path.parent.mkdir(parents=True, exist_ok=True)
test_failures_dir = module_snapshot_failures_dir / snapshot_file_name
if test_failures_dir.exists():
# Remove the past runs failure dir for this specific screenshot
shutil.rmtree(test_failures_dir)
if not snapshot_file_path.exists():
snapshot_file_path.write_bytes(img_bytes)
# Update this in updates folder:
snapshot_updates_file_path.parent.mkdir(parents=True, exist_ok=True)
snapshot_updates_file_path.write_bytes(img_bytes)
# For missing snapshots, we don't want to directly fail in order to generate
# all missing snapshots in one run.
test_failure_messages.append(f"Missing snapshot for {snapshot_file_name}")
return
from pixelmatch.contrib.PIL import pixelmatch
# Compare the new screenshot with the screenshot from past runs:
img_a = Image.open(BytesIO(img_bytes))
img_b = Image.open(snapshot_file_path)
img_diff = Image.new("RGBA", img_a.size)
error_msg: str = "Unknown error"
try:
mismatch = pixelmatch(
img_a,
img_b,
img_diff,
threshold=pixel_threshold,
fail_fast=fail_fast,
alpha=0,
)
total_pixels = img_a.size[0] * img_a.size[1]
max_diff_pixels = int(image_threshold * total_pixels)
if mismatch < max_diff_pixels:
return
error_msg = (
f"Snapshot mismatch for {snapshot_file_name} ({mismatch} pixels difference;"
f" {mismatch / total_pixels * 100:.2f}%)"
)
# Create new failures folder for this test:
test_failures_dir.mkdir(parents=True, exist_ok=True)
img_diff.save(
f"{test_failures_dir}/diff_{snapshot_file_name}{file_extension}"
)
img_a.save(
f"{test_failures_dir}/actual_{snapshot_file_name}{file_extension}"
)
img_b.save(
f"{test_failures_dir}/expected_{snapshot_file_name}{file_extension}"
)
except ValueError as ex:
# Create new failures folder for this test:
test_failures_dir.mkdir(parents=True, exist_ok=True)
img_a.save(
f"{test_failures_dir}/actual_{snapshot_file_name}{file_extension}"
)
img_b.save(
f"{test_failures_dir}/expected_{snapshot_file_name}{file_extension}"
)
# ValueError is thrown when the images have different sizes
# Calculate the relative difference in total pixels
expected_pixels = img_b.size[0] * img_b.size[1]
actual_pixels = img_a.size[0] * img_a.size[1]
pixel_diff = abs(expected_pixels - actual_pixels)
error_msg = (
f"Snapshot mismatch for {snapshot_file_name}. "
f"Wrong size: expected={img_b.size}, actual={img_a.size} "
f"({pixel_diff} pixels difference; "
f"{pixel_diff / expected_pixels * 100:.2f}%). "
f"Error: {ex}"
)
if is_last_rerun:
# If its the last rerun (or the only test run), update snapshots
# and fail after all the other snapshots have been updated in the given
# test.
snapshot_updates_file_path.parent.mkdir(parents=True, exist_ok=True)
snapshot_updates_file_path.write_bytes(img_bytes)
# Add error to the list of test failures:
test_failure_messages.append(error_msg)
else:
# If there are other test reruns that will follow, fail immediately
# and avoid updating the snapshot. Failing here will correctly show a
# test error in the Github UI, which enables our flaky test tracking
# tool to work correctly.
pytest.fail(error_msg)
yield compare
if test_failure_messages:
pytest.fail(
"Missing or mismatched snapshots: \n" + "\n".join(test_failure_messages)
)
@pytest.fixture(autouse=True)
def playwright_profiling(
request: pytest.FixtureRequest, page: Page
) -> Generator[None, None, None]:
if request.node.get_closest_marker("no_perf") or not is_supported_browser(page):
yield
return
with measure_performance(page, test_name=request.node.name):
yield
# endregion
# region Public utility methods
def wait_for_app_run(
page_or_locator: Page | Locator | FrameLocator,
wait_delay: int = 100,
initial_wait: int = 210,
) -> None:
"""Wait for the given page to finish running.
Parameters
----------
page_or_locator : Page | Locator | FrameLocator
The page or locator to wait for.
wait_delay : int, optional
The delay to wait for the rerun to finish.
initial_wait : int, optional
The initial wait before checking for the rerun to finish.
This is needed for some widgets that have a debounce timeout.
For example, pydeck charts have a debounce timeout of 200ms.
"""
page: Page
if isinstance(page_or_locator, Locator):
page = page_or_locator.page
elif isinstance(page_or_locator, FrameLocator):
page = page_or_locator.owner.page
else:
page = page_or_locator
page.wait_for_timeout(initial_wait)
if isinstance(page_or_locator, StaticPage):
# Check that static connection established.
page_or_locator.locator(
"[data-testid='stApp'][data-test-connection-state='STATIC_CONNECTED']"
).wait_for(
timeout=25000,
state="attached",
)
else:
# Make sure that the websocket connection is established.
page_or_locator.locator(
"[data-testid='stApp'][data-test-connection-state='CONNECTED']"
).wait_for(
timeout=25000,
state="attached",
)
# Wait until we know the script has started. We determine this by checking
# whether the app is in notRunning state. (The data-test-connection-state attribute
# goes through the sequence "initial" -> "running" -> "notRunning").
page_or_locator.locator(
"[data-testid='stApp'][data-test-script-state='notRunning']"
).wait_for(
timeout=25000,
state="attached",
)
# Wait for all element skeletons to be removed.
# This is useful to make sure that all elements have been rendered.
expect(page_or_locator.get_by_test_id("stSkeleton")).to_have_count(0, timeout=25000)
if wait_delay > 0:
# Give the app a little more time to render everything
page.wait_for_timeout(wait_delay)
def wait_for_app_loaded(page: Page) -> None:
"""Wait for the app to fully load."""
# Wait for the app view container to appear:
page.wait_for_selector(
"[data-testid='stAppViewContainer']", timeout=30000, state="attached"
)
wait_for_app_run(page)
def rerun_app(page: Page) -> None:
"""Triggers an app rerun and waits for the run to be finished."""
# Click somewhere to clear the focus from elements:
page.get_by_test_id("stApp").click(position={"x": 0, "y": 0})
# Press "r" to rerun the app:
page.keyboard.press("r")
wait_for_app_run(page)
def wait_until(
page: Page, fn: Callable[[], None | bool], timeout: int = 5000, interval: int = 100
) -> None:
"""Run a test function in a loop until it evaluates to True
or times out.
For example:
>>> wait_until(lambda: x.values() == ["x"], page)
Parameters
----------
page : playwright.sync_api.Page
Playwright page
fn : Callable
Callback
timeout : int, optional
Total timeout in milliseconds, by default 5000
interval : int, optional
Waiting interval, by default 100
Adapted from panel.
"""
# Hide this function traceback from the pytest output if the test fails
__tracebackhide__ = True
start = time.time()
def timed_out() -> bool:
elapsed = time.time() - start
elapsed_ms = elapsed * 1000
return elapsed_ms > timeout
timeout_msg = f"wait_until timed out in {timeout} milliseconds"
while True:
try:
result = fn()
except AssertionError as e:
if timed_out():
raise TimeoutError(timeout_msg) from e
else:
if result not in (None, True, False):
raise ValueError(
"`wait_until` callback must return None, True or "
f"False, returned {result!r}"
)
# Stop is result is True or None
# None is returned when the function has an assert
if result is None or result:
return
if timed_out():
raise TimeoutError(timeout_msg)
page.wait_for_timeout(interval)
def start_app_server(
app_port: int,
request_module: ModuleType,
*,
extra_env: dict[str, str] | None = None,
extra_args: list[str] | None = None,
) -> AsyncSubprocess:
"""Start a Streamlit app server for the given *test module*.
This helper centralizes the logic for spinning up a Streamlit subprocess so
it can be reused by different pytest fixtures (for example, tests that
require per-test environment variables).
Parameters
----------
app_port : int
Port on which the server should listen.
request_module : ModuleType
The pytest *module object* that triggered the server start. This is
needed to resolve the Streamlit script that belongs to the test.
extra_env : dict[str, str] | None, optional
Additional environment variables to set for the subprocess.
extra_args : list[str] | None, optional
Additional command-line arguments to pass to *streamlit run*.
Returns
-------
AsyncSubprocess
The running Streamlit subprocess wrapper. *Call ``terminate()`` on the
returned object to stop the server and obtain the captured output.*
"""
env = {**os.environ.copy(), **(extra_env or {})}
args = [
"streamlit",
"run",
resolve_test_to_script(request_module),
"--server.headless",
"true",
"--global.developmentMode",
"false",
"--global.e2eTest",
"true",
"--server.port",
str(app_port),
"--browser.gatherUsageStats",
"false",
"--server.fileWatcherType",
"none",
"--server.enableStaticServing",
"true",
]
app_server_start_retries = 3
app_server_start_retry_delay_seconds = 20
# Append any caller-supplied extra args at the end so they can override
# defaults when necessary.
if extra_args:
args.extend(extra_args)
for i in range(app_server_start_retries):
proc = AsyncSubprocess(args, cwd=".", env=env)
proc.start()
if wait_for_app_server_to_start(app_port):
return proc
stdout = proc.terminate()
print(stdout, flush=True)
if i < app_server_start_retries - 1:
print(
f"Retrying to start app server in {app_server_start_retry_delay_seconds} seconds... "
f"(Attempt {i + 1}/{app_server_start_retries})",
flush=True,
)
time.sleep(app_server_start_retry_delay_seconds)
raise RuntimeError("Unable to start Streamlit app")
# endregion
| 17,183
|
streamlit
|
streamlit/e2e_playwright/custom_components/component_errors_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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, Route, expect
from e2e_playwright.conftest import wait_until
# The timeout value from ComponentInstance.tsx
COMPONENT_READY_WARNING_TIME_MS = 60000 # 60 seconds
def handle_component_source_failure(route: Route):
"""Handle custom component source request by returning a 404 status."""
route.fulfill(status=404, headers={"Content-Type": "text/plain"}, body="Not Found")
def handle_component_timeout_failure(route: Route):
"""Handle custom component request by aborting the request (trigger catch in fetch)."""
route.abort("failed")
def test_component_source_failure(page: Page, app_port: int):
"""Test that a component source failure is handled correctly."""
# Ensure custom component source requests return a 404 status
page.route(
f"http://localhost:{app_port}/component/**", handle_component_source_failure
)
# Capture console messages
messages = []
page.on("console", lambda msg: messages.append(msg.text))
# Navigate to the app
page.goto(f"http://localhost:{app_port}")
# Expect the iframe to be attached
# Use a higher timeout since the goto triggers a rerun which sometimes can take
# > 5 seconds.
expect(page.get_by_test_id("stCustomComponentV1")).to_be_attached(timeout=10000)
# Wait until the expected error is logged, which indicates CLIENT_ERROR was sent
wait_until(
page,
lambda: any(
"Client Error: Custom Component streamlit_ace.streamlit_ace source error"
in message
for message in messages
),
)
def test_component_timeout_failure(page: Page, app_port: int):
"""Test that a component timeout failure is handled correctly."""
# Ensure custom component requests times out
page.route(
f"http://localhost:{app_port}/component/**", handle_component_timeout_failure
)
# Capture console messages
messages = []
page.on("console", lambda msg: messages.append(msg.text))
# Navigate to the app
page.goto(f"http://localhost:{app_port}")
# Expect the iframe to be attached
# Use a higher timeout since the goto triggers a rerun which sometimes can take
# > 5 seconds.
expect(page.get_by_test_id("stCustomComponentV1")).to_be_attached(timeout=10000)
# Fetch error should be logged
wait_until(
page,
lambda: any(
"Client Error: Custom Component streamlit_ace.streamlit_ace fetch error"
in message
for message in messages
),
)
# Wait for the component to timeout
page.wait_for_timeout(COMPONENT_READY_WARNING_TIME_MS)
wait_until(
page,
lambda: any(
"Client Error: Custom Component streamlit_ace.streamlit_ace timeout error"
in message
for message in messages
),
)
# Wait for the warning to appear and verify
expect(page.get_by_test_id("stAlert")).to_be_visible()
| 1,233
|
streamlit
|
streamlit/e2e_playwright/custom_components/pdf_component.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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]()
| 2,014
|
streamlit
|
streamlit/e2e_playwright/custom_components/pdf_component_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
def _select_pdf_scenario(app: Page, scenario: str):
"""Select a PDF test scenario from the dropdown."""
selectbox_input = app.get_by_test_id("stSelectbox").locator("input")
selectbox_input.clear()
selectbox_input.type(scenario)
selectbox_input.press("Enter")
wait_for_app_run(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")
| 4,939
|
streamlit
|
streamlit/e2e_playwright/custom_components/popular_components.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 the components logic and that custom components work.
This test app includes some component actions as well as the top N most popular custom
components based on our usage metrics.
The function for the component is imported when the respective option is selected in the
selection-widget. Also, some example action is executed on the component.
If the component cannot be imported or the component itself has some issue, e.g.
some transitive import does not work, an exception is shown.
This is some guard for us to detect potential issues in case of refactorings etc.
Following actions/components are tested:
- components.html (this function and its import is popularily documented in some places)
- extra-streamlit-components (CookieManager)
- streamlit-ace
- streamlit-antd-components
- streamlit-aggrid
- streamlit-autorefresh
- streamlit-chat
- streamlit-echarts
- streamlit-folium
- streamlit-option-menu
- streamlit-url-fragment
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import streamlit as st
if TYPE_CHECKING:
from collections.abc import Callable
def use_components_html():
# note that we import streamlit before and so this `components.html` working
# might be coincidental; this is the reason why we have dedicated tests for this
# kind of imports in the `st_components_v1_*` files
import streamlit.components.v1 as components
components.html("<div>Hello World!</div>")
def use_components_iframe():
# note that we import streamlit before and so this `components.html` working
# might be coincidental; this is the reason why we have dedicated tests for this
# kind of imports in the `st_components_v1_*` files
import streamlit.components.v1 as components
st.write(str(components.iframe))
def use_components_declare_component():
import streamlit.components.v1 as components
st.write(str(components.declare_component))
# Different custom components:
def use_streamlit_ace():
from streamlit_ace import st_ace # type: ignore
## Spawn a new Ace editor
content = st_ace()
st.write(content)
def use_aggrid():
import numpy as np
import pandas as pd
from st_aggrid import AgGrid # type: ignore
np.random.seed(0)
df = pd.DataFrame(
np.random.choice(100, size=(100, 4)), columns=["A", "B", "C", "D"]
)
AgGrid(df, height=200)
def use_antd():
import streamlit_antd_components as sac # type: ignore
btn = sac.buttons(
items=["button1", "button2", "button3"],
index=0,
format_func="title",
align="center",
direction="horizontal",
radius="lg",
return_index=False,
)
st.write(f"The selected button label is: {btn}")
def use_autorefresh():
from streamlit_autorefresh import st_autorefresh # type: ignore
## Run the autorefresh about every 2000 milliseconds (2 seconds) and stop
## after it's been refreshed 100 times.
count = st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter")
## The function returns a counter for number of refreshes. This allows the
## ability to make special requests at different intervals based on the count
if count == 0:
st.write("Count is zero")
elif count % 3 == 0 and count % 5 == 0:
st.write("FizzBuzz")
elif count % 3 == 0:
st.write("Fizz")
elif count % 5 == 0:
st.write("Buzz")
else:
st.write(f"Count: {count}")
def use_chat():
from streamlit_chat import message # type: ignore
message("My message")
message("Hello bot!", is_user=True) # align's the message to the right
def use_echarts():
from streamlit_echarts import st_echarts # type: ignore
options = {
"xAxis": {
"type": "category",
"data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
"yAxis": {"type": "value"},
"series": [{"data": [820, 932, 901, 934, 1290, 1330, 1320], "type": "line"}],
}
st_echarts(options=options)
def use_extra_streamlit_components():
from extra_streamlit_components import CookieManager # type: ignore
CookieManager()
def use_folium():
import folium # type: ignore
from streamlit_folium import st_folium # type: ignore
## center on Liberty Bell, add marker
m = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
folium.Marker(
[39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell"
).add_to(m)
## call to render Folium map in Streamlit
st_data = st_folium(m, width=725)
st.write(st_data)
def use_option_menu():
from streamlit_option_menu import option_menu # type: ignore
key = "my_option_menu"
def on_change(key: str) -> None:
selection = st.session_state[key]
st.write(f"Selection changed to {selection}")
with st.sidebar:
selected = option_menu(
"Main Menu",
["Home", "Settings"],
icons=["house", "gear"],
menu_icon="cast",
default_index=1,
key=key,
on_change=on_change,
)
st.write(selected)
def use_url_fragment():
from streamlit_url_fragment import get_fragment # type: ignore
current_value = get_fragment()
st.write(f"Current value: {current_value!r}")
def use_bokeh():
from bokeh.plotting import figure # type: ignore
from streamlit_bokeh import streamlit_bokeh # type: ignore
# Data
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
# Create Bokeh figure
bokeh_figure = figure(
title="Simple Line Example", x_axis_label="x", y_axis_label="y"
)
bokeh_figure.line(x, y, legend_label="Trend", line_width=2)
# Render in Streamlit
streamlit_bokeh(
bokeh_figure,
use_container_width=True,
theme="streamlit",
key="my_unique_key",
)
# ---
options: dict[str, Callable[[], None]] = {
"componentsHtml": use_components_html,
"componentsIframe": use_components_iframe,
"componentsDeclareComponent": use_components_declare_component,
"ace": use_streamlit_ace,
"aggrid": use_aggrid,
"antd": use_antd,
"autorefresh": use_autorefresh,
"chat": use_chat,
"echarts": use_echarts,
"extraStreamlitComponents": use_extra_streamlit_components,
"folium": use_folium,
"optionMenu": use_option_menu,
"urlFragment": use_url_fragment,
"bokeh": use_bokeh,
}
component_selection = st.selectbox("ComponentSelections", options=options.keys())
if component_selection:
options[component_selection]()
| 2,670
|
streamlit
|
streamlit/e2e_playwright/custom_components/popular_components_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 re
import pytest
from playwright.sync_api import Page, expect
from e2e_playwright.conftest import wait_for_app_run
def _select_component(app: Page, component: str):
selectbox_input = app.get_by_test_id("stSelectbox").locator("input")
# Type an option (defined in the test app):
selectbox_input.type(component)
selectbox_input.press("Enter")
wait_for_app_run(app)
def _expect_no_exception(app: Page):
"""If there is an issue with importing / using the custom component, Streamlit
throws an exception. So, expect that no exception was thrown.
"""
expect(app.get_by_test_id("stException")).not_to_be_visible()
def _expect_iframe_attached(app: Page):
"""Expect the CustomComponent iframe to be attached to the DOM."""
expect(app.locator("iframe").first).to_be_attached()
def test_components_html(app: Page):
"""Test that components.html can be imported and used."""
_select_component(app, "componentsHtml")
_expect_no_exception(app)
_expect_iframe_attached(app)
iframe = app.frame_locator("iframe")
div = iframe.locator("div")
expect(div).to_have_text("Hello World!")
@pytest.mark.parametrize(
("name", "expected_text"),
[
("componentsIframe", "bound method IframeMixin._iframe of DeltaGenerator()"),
("componentsDeclareComponent", "function declare_component at"),
],
)
def test_components_import(app: Page, name: str, expected_text: str):
"""Test that components.iframe and components.declare_component can be imported
and used.
We only make sure that they are importable but do not call them, so we don't have
an iframe element in the DOM.
"""
_select_component(app, name)
_expect_no_exception(app)
div = app.get_by_test_id("stMarkdownContainer").filter(
has_text=re.compile(f"<{expected_text}.*>")
)
expect(div).to_be_attached()
def test_ace(app: Page):
"""Test that the ace component renders."""
_select_component(app, "ace")
_expect_no_exception(app)
_expect_iframe_attached(app)
def test_aggrid(app: Page):
"""Test that the aggrid component renders."""
_select_component(app, "aggrid")
_expect_no_exception(app)
_expect_iframe_attached(app)
def test_antd(app: Page):
"""Test that the ace component renders."""
_select_component(app, "antd")
_expect_no_exception(app)
_expect_iframe_attached(app)
def test_autorefresh(app: Page):
"""Test that the autorefresh component renders."""
_select_component(app, "autorefresh")
_expect_no_exception(app)
def test_chat(app: Page):
"""Test that the chat component renders."""
_select_component(app, "chat")
_expect_iframe_attached(app)
def test_echarts(app: Page):
"""Test that the echarts component renders."""
_select_component(app, "echarts")
_expect_no_exception(app)
def test_extra_streamlit_components(app: Page):
"""Test that the extra-strealit-components component renders."""
_select_component(app, "extraStreamlitComponents")
_expect_no_exception(app)
_expect_iframe_attached(app)
def test_folium(app: Page):
"""Test that the folium component renders."""
_select_component(app, "folium")
_expect_no_exception(app)
_expect_iframe_attached(app)
def test_option_menu(app: Page):
"""Test that the option-menu component renders."""
_select_component(app, "optionMenu")
_expect_no_exception(app)
_expect_iframe_attached(app)
frame_locator = app.frame_locator("iframe")
frame_locator.locator("a", has_text="Home").click()
expect(
app.get_by_test_id("stMarkdown").filter(has_text="Selection changed to Home")
).to_be_visible()
def test_url_fragment(app: Page):
"""Test that the url-fragment component renders."""
_select_component(app, "urlFragment")
_expect_no_exception(app)
_expect_iframe_attached(app)
def test_bokeh(app: Page):
"""Test that the bokeh component renders."""
_select_component(app, "bokeh")
_expect_no_exception(app)
_expect_iframe_attached(app)
| 1,708
|
streamlit
|
streamlit/e2e_playwright/deploy_dialog_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 wait_for_all_images_to_be_loaded
def test_deploy_button_displays_correctly(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
deploy_button = themed_app.get_by_test_id("stAppDeployButton")
deploy_button.click()
# Make sure that deploy dialog is properly displayed
# Before taking screenshot
deploy_dialog = themed_app.get_by_test_id("stDialog")
expect(deploy_dialog).to_be_visible()
expect(
deploy_dialog.get_by_test_id("stDeployDialogCommunityCloudIcon")
).to_be_visible()
expect(
deploy_dialog.get_by_test_id("stDeployDialogCustomDeploymentIcon")
).to_be_visible()
wait_for_all_images_to_be_loaded(themed_app)
# Make a snapshot of the dialog window
assert_snapshot(deploy_dialog.get_by_role("dialog"), name="deploy_dialog")
| 518
|
streamlit
|
streamlit/e2e_playwright/forward_msg_cache.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 pandas as pd
import streamlit as st
if "rerun_count" not in st.session_state:
st.session_state["rerun_count"] = 0
st.session_state["rerun_count"] += 1
# Send a ForwardMsg to the client that's long enough that we cache it.
num_small_messages = st.number_input(
"Number of small messages", value=50, min_value=1, max_value=200
)
kb_message_size = st.number_input(
"Message KB size", value=50, min_value=1, max_value=200
)
# This string is ~1kb in size if rendered via markdown:
message_1kb = "\n\n".join(
2
* [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis neque "
"eu orci faucibus pellentesque. Vivamus dapibus pellentesque sem, vitae "
"ultricies sem pharetra at. Curabitur eu congue magna, eu tempor libero. "
"Donec vitae condimentum odio. Sed neque elit, porttitor eget laoreet "
"volutpat, imperdiet et leo. Phasellus vel velit sit amet nulla hendrerit "
"pharetra et non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing "
"elit. In malesuada sem sit amet felis vestibulum, maximus."
]
)
with st.container(height=300):
for i in range(num_small_messages):
st.markdown(
f"**Message {i + 1}:** \n\n" + "\n\n".join(kb_message_size * [message_1kb]),
)
@st.fragment
def my_fragment():
st.button("Rerun fragment")
with st.expander("Message in Fragment", expanded=False):
st.markdown(
"**Message in Fragment:** \n\n"
+ "\n\n".join(kb_message_size * [message_1kb]),
)
my_fragment()
st.button("Re-run")
st.markdown(f"Rerun count: {st.session_state['rerun_count']}")
if st.toggle("Show dataframes"):
# With the default settings, the dataframe is ~50MB in size.
num_cols = st.number_input("Number of columns", value=20, min_value=1, max_value=40)
num_rows = st.number_input(
"Number of rows", value=100000, min_value=1, max_value=500000
)
# Create a large dataframe
@st.cache_data
def create_large_dataframe(num_cols: int, num_rows: int) -> pd.DataFrame:
df = pd.DataFrame({f"col {i}": range(num_rows) for i in range(num_cols)})
# Make 50% of the columns string columns
for i in range(num_cols):
if i % 2 == 0:
df[f"col {i}"] = df[f"col {i}"].astype(str)
return df
df = create_large_dataframe(num_cols, num_rows)
st.dataframe(df)
st.data_editor(df)
| 1,246
|
streamlit
|
streamlit/e2e_playwright/forward_msg_cache_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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, Final
import pytest
from e2e_playwright.shared.app_utils import (
click_button,
click_toggle,
fill_number_input,
goto_app,
)
if TYPE_CHECKING:
from playwright.sync_api import Page, WebSocket
def _rerun_app(app: Page, times: int):
for _ in range(times):
click_button(app, "Re-run")
@pytest.mark.performance
@pytest.mark.repeat(2) # only repeat 2 times since otherwise it would take too long
def test_simulate_large_data_usage_performance(app: Page):
# Rerun app a couple of times:
_rerun_app(app, 5)
# Show dataframe:
click_toggle(app, "Show dataframes")
# Rerun app a couple of times:
_rerun_app(app, 5)
# # Set 50k rows:
fill_number_input(app, "Number of rows", 50000)
# Rerun app a couple of times:
_rerun_app(app, 5)
# Show more text messages:
fill_number_input(app, "Number of small messages", 100)
# Rerun app a couple of times:
_rerun_app(app, 10)
@pytest.mark.performance
@pytest.mark.repeat(2) # only repeat 2 times since otherwise it would take too long
def test_simulate_many_small_messages_performance(app: Page):
# Show 150 unique texts with 50kb each:
fill_number_input(app, "Number of small messages", 150)
_rerun_app(app, 5)
# Reduce the size of every message to 15KB:
fill_number_input(app, "Message KB size", 15)
_rerun_app(app, 10)
def test_check_total_websocket_message_number_and_size(page: Page, app_port: int):
"""Test that verifies the number and total size of websocket messages
during the simluated forward message cache run is under a configured threshold.
"""
# Define an acceptable threshold for total websocket message size (in MB)
# for a simulated forward message cache run with large messages.
# If the threshold is exceeded significantly, it might indicate a bug with
# the forward message cache. You can modify this threshold if it's needed,
# justified, and expected.
# BackMsg's
TOTAL_WEBSOCKET_SENT_SIZE_THRESHOLD_MB: Final = 0.1 # noqa: N806
# Number of websocket messages sent
EXPECTED_WEBSOCKET_MESSAGES_SENT: Final = 34 # noqa: N806
# ForwardMsg's
TOTAL_WEBSOCKET_RECEIVED_SIZE_THRESHOLD_MB: Final = 55 # noqa: N806
# Max number of websocket messages received.
EXPECTED_WEBSOCKET_MESSAGES_RECEIVED: Final = 2540 # noqa: N806
# There can be a bit of fluctuation because of optimization logic:
# See the composable messages logic in
# lib/streamlit/runtime/forward_msg_queue.py (-> `_maybe_compose_delta_msgs`)
# the queues can be flushed to the browser before
# the optimization is able to be applied.
ALLOWED_WEBSOCKET_MESSAGES_RECEIVED_DIFFERENCE: Final = 25 # noqa: N806
total_websocket_sent_size_bytes: int = 0
total_websocket_received_size_bytes: int = 0
total_websocket_messages_sent: int = 0
total_websocket_messages_received: int = 0
def on_web_socket(ws: WebSocket) -> None:
print(f"WebSocket opened: {ws.url}")
def on_frame_sent(payload: str | bytes):
nonlocal total_websocket_sent_size_bytes
nonlocal total_websocket_messages_sent
if isinstance(payload, str):
payload = payload.encode("utf-8")
total_websocket_sent_size_bytes += len(payload)
total_websocket_messages_sent += 1
def on_frame_received(payload: str | bytes):
nonlocal total_websocket_received_size_bytes
nonlocal total_websocket_messages_received
if isinstance(payload, str):
payload = payload.encode("utf-8")
total_websocket_received_size_bytes += len(payload)
total_websocket_messages_received += 1
ws.on("framesent", on_frame_sent)
ws.on("framereceived", on_frame_received)
ws.on("close", lambda _: print("WebSocket closed"))
# Register websocket handler
page.on("websocket", on_web_socket)
goto_app(page, f"http://localhost:{app_port}/")
# Wait until all dependent resources are loaded:
page.wait_for_load_state()
# Rerun app a couple of times:
_rerun_app(page, 5)
# Show dataframe:
click_toggle(page, "Show dataframes")
# Rerun app a couple of times:
_rerun_app(page, 5)
# # Set 50k rows:
fill_number_input(page, "Number of rows", 50000)
# Rerun fragment a couple of times:
click_button(page, "Rerun fragment")
click_button(page, "Rerun fragment")
click_button(page, "Rerun fragment")
click_button(page, "Rerun fragment")
click_button(page, "Rerun fragment")
# -> Running fragments should not clear cached messages of non-fragments
# Rerun app a couple of times:
_rerun_app(page, 5)
# Show more text messages:
fill_number_input(page, "Number of small messages", 100)
# Rerun app a couple of times:
_rerun_app(page, 10)
# Assert that the total number of websocket messages received and sent is equal
assert (
abs(total_websocket_messages_received - EXPECTED_WEBSOCKET_MESSAGES_RECEIVED)
< ALLOWED_WEBSOCKET_MESSAGES_RECEIVED_DIFFERENCE
), (
f"Total number of websocket messages received by the frontend "
f"{total_websocket_messages_received} but expected to receive"
f"{EXPECTED_WEBSOCKET_MESSAGES_RECEIVED} +/- "
f"{ALLOWED_WEBSOCKET_MESSAGES_RECEIVED_DIFFERENCE}. In case this is expected, "
"you can change the number in the test."
)
assert total_websocket_messages_sent == EXPECTED_WEBSOCKET_MESSAGES_SENT, (
f"Total number of websocket messages sent by the frontend "
f"{total_websocket_messages_sent} but expected to send "
f"{EXPECTED_WEBSOCKET_MESSAGES_SENT}. In case this is expected, "
"you can change the number in the test."
)
# Assert that the total size of websocket messages is under the threshold:
assert (
total_websocket_received_size_bytes
< TOTAL_WEBSOCKET_RECEIVED_SIZE_THRESHOLD_MB * 1024 * 1024
), (
f"Total received size of websocket messages "
f"({total_websocket_received_size_bytes / 1024 / 1024:.2f}MB) "
"exceeds the configured threshold "
f"({TOTAL_WEBSOCKET_RECEIVED_SIZE_THRESHOLD_MB}MB)"
"In case this is expected and justified, you can change the "
"threshold in the test."
)
assert (
total_websocket_sent_size_bytes
< TOTAL_WEBSOCKET_SENT_SIZE_THRESHOLD_MB * 1024 * 1024
), (
"Total sent size of websocket messages "
f"({total_websocket_sent_size_bytes / 1024 / 1024:.2f}MB) "
"exceeds the configured threshold "
f"({TOTAL_WEBSOCKET_SENT_SIZE_THRESHOLD_MB}MB)"
"In case this is expected and justified, you can change the "
"threshold in the test."
)
| 2,913
|
streamlit
|
streamlit/e2e_playwright/hello_app_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.vega_utils import assert_vega_chart_height
def navigate_to_page(app: Page, index: int):
app.get_by_test_id("stSidebarNav").locator("a").nth(index).click()
wait_for_app_run(app)
# Move the mouse to the top left corner to prevent any weird hover effects
# in the screenshots
app.mouse.move(0, 0)
def check_page_title(app: Page, title: str) -> None:
expect(
app.get_by_test_id("stMarkdownContainer").locator("h1").nth(0)
).to_contain_text(title)
def check_page_icon(app: Page, icon: str, index: int = 0) -> None:
expect(
app.get_by_test_id("stSidebarNavLink")
.get_by_test_id("stIconMaterial")
.nth(index)
).to_have_text(icon)
def test_home_page(app: Page, assert_snapshot: ImageCompareFunction) -> None:
"""Test that the home page of the hello app is displayed correctly."""
check_page_title(app, "Welcome to Streamlit!")
check_page_icon(app, "waving_hand")
expect(app.get_by_test_id("stSidebar")).to_be_visible()
expect(app.get_by_test_id("stSidebarNav")).to_be_visible()
assert_snapshot(app, name="hello_app-home_page")
def test_animation_demo_page(app: Page, assert_snapshot: ImageCompareFunction) -> None:
"""Test that the animation demo page of the hello app is displayed correctly."""
navigate_to_page(app, 4)
check_page_title(app, "Animation demo")
check_page_icon(app, "animation", 4)
# Wait for the animation to end. The animation takes 5-10 seconds to finish
# which is a lot more than the default timeout, so we set it to a higher value
expect(app.get_by_test_id("stButton")).to_contain_text("Rerun", timeout=25000)
assert_snapshot(app, name="hello_app-animation_demo_page")
def test_plotting_demo_page(app: Page, assert_snapshot: ImageCompareFunction) -> None:
"""Test that the plotting demo page of the hello app is displayed correctly."""
navigate_to_page(app, 2)
check_page_title(app, "Plotting demo")
check_page_icon(app, "show_chart", 2)
# The animation takes 5-10 seconds to finish, so we add
# and additional timeout
expect(app.get_by_test_id("stText")).to_contain_text("100% complete", timeout=15000)
expect(app.get_by_test_id("stProgress")).not_to_be_visible()
assert_vega_chart_height(app.get_by_test_id("stVegaLiteChart"), 350)
assert_snapshot(app, name="hello_app-plotting_demo_page")
def test_mapping_demo_page(app: Page) -> None:
"""Test that the mapping demo page of the hello app is displayed correctly."""
navigate_to_page(app, 3)
check_page_title(app, "Mapping demo")
check_page_icon(app, "public", 3)
# We add an additional timeout here since sometimes the loading of
# the map takes a bit longer (probably because of the map token request).
expect(
app.get_by_test_id("stElementContainer").filter(
has=app.get_by_test_id("stDeckGlJsonChart")
)
).to_have_css("height", "500px", timeout=10000)
# The snapshot test here is flaky, the map doesn't seem to always result
# in the same image.
# assert_snapshot(app, name="hello_app-mapping_demo_page") # noqa: ERA001
def _load_dataframe_demo_page(app: Page):
"""Load the dataframe demo page and wait until all elements are visible."""
navigate_to_page(app, 1)
check_page_title(app, "DataFrame demo")
check_page_icon(app, "table", 1)
expect(app.get_by_test_id("stMultiSelect")).to_be_visible()
expect(app.get_by_test_id("stDataFrame")).to_be_visible()
assert_vega_chart_height(app.get_by_test_id("stVegaLiteChart"), 350)
def test_dataframe_demo_page(app: Page, assert_snapshot: ImageCompareFunction) -> None:
"""Test that the dataframe demo page of the hello app is displayed correctly."""
_load_dataframe_demo_page(app)
assert_snapshot(app, name="hello_app-dataframe_demo_page")
# TEST PRINTING:
# The print tests are in this suite to avoid having full-app screenshots being spread
# around in different suites. Even the smallest design change in one part of the app can
# make these full-screenshots fail and require renewal, which is why we want them to be
# bundled in one place. The "Dataframe Demo" page was arbitrarily chosen as a good
# printing candidate.
def _evaluate_match_media_print(app: Page):
app.evaluate("matchMedia('print').matches")
# DIN A4 paper is 21cm x 29.7cm which is 595px x 842px in 72dpi;
# Use higher pixels to avoid mobile media queries to trigger but keep the ratio
portrait_width_px = 1240
portrait_height_px = 1754
def _set_portrait_dimensions(app: Page):
app.set_viewport_size({"width": portrait_width_px, "height": portrait_height_px})
def _set_landscape_dimensions(app: Page):
app.set_viewport_size({"width": portrait_height_px, "height": portrait_width_px})
def test_app_print_mode_portrait_with_sidebar_open(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that the dataframe demo page looks correctly in print-mode with
sidebar open.
"""
app = themed_app
_load_dataframe_demo_page(app)
app.emulate_media(media="print", forced_colors="active")
_set_portrait_dimensions(app)
_evaluate_match_media_print(app)
# ensure that the sidebar is visible
expect(app.get_by_test_id("stSidebar")).to_be_visible()
expect(app.get_by_test_id("stSidebarContent")).to_be_visible()
assert_snapshot(app, name="hello_app-print_media-portrait-sidebar_open")
def test_app_print_mode_portrait_with_sidebar_closed(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that the dataframe demo page looks correctly in print-mode with
sidebar closed.
"""
app = themed_app
# Note: this was moved up to the top because the sidebar has logic that when
# resizing the window could cause the sidebar to be open or closed
_set_portrait_dimensions(app)
_load_dataframe_demo_page(app)
# close sidebar. Must be done before print-mode, because we hide the close button
# when printing
sidebar_element = app.get_by_test_id("stSidebar")
sidebar_element.hover()
app.get_by_test_id("stSidebarCollapseButton").click()
expect(sidebar_element).not_to_be_visible()
app.emulate_media(media="print", forced_colors="active")
_evaluate_match_media_print(app)
assert_snapshot(app, name="hello_app-print_media-portrait-sidebar_closed")
def test_app_print_mode_landscape_with_sidebar_open(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that the dataframe demo page looks correctly in print-mode
(orientation: landscape) with sidebar open.
"""
app = themed_app
_load_dataframe_demo_page(app)
app.emulate_media(media="print", forced_colors="active")
_set_landscape_dimensions(app)
_evaluate_match_media_print(app)
# ensure that the sidebar is visible
expect(app.get_by_test_id("stSidebar")).to_be_visible()
expect(app.get_by_test_id("stSidebarContent")).to_be_visible()
assert_snapshot(app, name="hello_app-print_media-landscape-sidebar_open")
def test_app_print_mode_landscape_with_sidebar_closed(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that the dataframe demo page looks correctly in print-mode
(orientation: landscape) with sidebar closed.
"""
app = themed_app
# Note: this was moved up to the top because the sidebar has logic that when
# resizing the window could cause the sidebar to be open or closed
_set_landscape_dimensions(app)
_load_dataframe_demo_page(app)
# close sidebar. Must be done before print-mode, because we hide the close button
# when printing
sidebar_element = app.get_by_test_id("stSidebar")
sidebar_element.hover()
app.get_by_test_id("stSidebarCollapseButton").click()
expect(sidebar_element).not_to_be_visible()
app.emulate_media(media="print", forced_colors="active")
_evaluate_match_media_print(app)
assert_snapshot(app, name="hello_app-print_media-landscape-sidebar_closed")
def test_max_content_width_uses_px(app: Page):
"""Test that the max content width uses px and not rem.
We don't want to adjust the content max width based on the root font size,
therefore, we are changing this setting to px instead of rem. This allows
us to fill the same screen estate regardless of the root font size
-> which allows more compact apps by using a small font size.
"""
expect(app.get_by_test_id("stMainBlockContainer")).to_have_css("max-width", "736px")
| 3,253
|
streamlit
|
streamlit/e2e_playwright/help_tooltip.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.sidebar:
st.button(
label="Sidebar-button with help",
help="""This is a longer help text to inform users of the functionality and in
case it is disabled what to do to enable it. This is a longer help text
to inform users of the functionality and in case it is disabled what to
do to enable it.
""",
)
columns_ = st.columns([9, 1.5, 1.5])
with columns_[0]:
st.number_input(
"Tooltip with code test", 0, 10, 1, help="Tooltip `with some code` in it"
)
with columns_[1].popover("Some popover"):
pass
with columns_[2].popover("Popover with toggle"):
st.toggle(
"Right-toggle with help",
help="""
View statistics of all damage done at each skill level only.
This includes all damage done at each player level available at
each skill level.
""",
)
| 556
|
streamlit
|
streamlit/e2e_playwright/help_tooltip_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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_until
from e2e_playwright.shared.app_utils import get_checkbox
from e2e_playwright.shared.react18_utils import wait_for_react_stability
def test_tooltip_does_not_overflow_on_the_left_side(app: Page):
sidebar_button = (
app.get_by_test_id("stButton")
.filter(has_text="Sidebar-button with help")
.locator("button")
.first
)
sidebar_button.hover()
tooltip = app.get_by_test_id("stTooltipContent")
expect(tooltip).to_be_visible()
# Wait until the tooltip is positioned correctly
wait_until(
app, lambda: (bbox := tooltip.bounding_box()) is not None and bbox["x"] >= 0
)
def test_tooltip_does_not_overflow_on_the_right_side(app: Page):
# Resize the viewport to make sure there is not a lot of space on the right side
viewport_width = 750
app.set_viewport_size({"width": viewport_width, "height": 800})
app.wait_for_function(f"() => window.innerWidth === {viewport_width}")
# Wait for React to stabilize after viewport change
wait_for_react_stability(app)
popover_button = (
app.get_by_test_id("stPopover")
.filter(has_text="Popover with toggle")
.locator("button")
)
# Ensure popover button is visible and stable before clicking
expect(popover_button).to_be_visible()
# Click the button to open it:
popover_button.click()
# Wait for React to stabilize after opening popover
wait_for_react_stability(app)
toggle = get_checkbox(app, "Right-toggle with help")
expect(toggle).to_be_visible()
# Get the tooltip hover target and ensure it's visible before hovering
hover_target = toggle.get_by_test_id("stTooltipHoverTarget")
expect(hover_target).to_be_visible()
# Ensure UI is stable before hovering
wait_for_react_stability(app)
# Hover over the tooltip target
hover_target.hover()
# Wait for tooltip to appear and stabilize
app.wait_for_timeout(200)
tooltip = app.get_by_test_id("stTooltipContent")
expect(tooltip).to_be_visible()
# Wait for tooltip positioning to complete
wait_for_react_stability(app)
# Wait until the tooltip is positioned correctly
wait_until(
app,
lambda: (bbox := tooltip.bounding_box()) is not None
and bbox["x"] + bbox["width"] <= viewport_width,
)
def test_tooltip_with_code(app: Page):
"""Test that a help tooltip with code displays correctly."""
# Get the number input widget
number_input = app.get_by_test_id("stNumberInput")
# Hover over the tooltip target (?) to display the tooltip
hover_target = number_input.get_by_test_id("stTooltipHoverTarget")
hover_target.hover()
# Wait for tooltip to appear and stabilize
app.wait_for_timeout(200)
# Get the tooltip content
tooltip = app.get_by_test_id("stTooltipContent")
expect(tooltip).to_be_visible()
expect(tooltip).to_contain_text("Tooltip with some code in it")
# General tooltip text should have a size of 14px
expect(tooltip.get_by_text("Tooltip")).to_have_css("font-size", "14px")
# Inline code text should be set to 0.75em (which with tooltip font size
# of 14px translates to 10.5px)
expect(tooltip.get_by_role("code")).to_have_css("font-size", "10.5px")
| 1,397
|
streamlit
|
streamlit/e2e_playwright/host_config.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 pandas as pd
import streamlit as st
def page2():
st.header("Page 2")
def page3():
st.header("Page 3")
# Make MPA to use for dialog blocking test
st.navigation(
[
st.Page(page2, title="02_App_Page_2", default=True),
st.Page(page3, title="03_App_Page_3"),
]
)
# always generate the same data
np.random.seed(0)
st.image(np.repeat(0, 100).reshape(10, 10))
st.dataframe(
pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list("ABCD"))
)
| 388
|
streamlit
|
streamlit/e2e_playwright/host_config_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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, Route, expect
from e2e_playwright.conftest import (
ImageCompareFunction,
wait_until,
)
from e2e_playwright.shared.app_utils import goto_app
def handle_route_hostconfig_disable_fullscreen_and_error_dialogs(route: Route) -> None:
response = route.fetch()
body = response.json()
body["disableFullscreenMode"] = True
body["blockErrorDialogs"] = True
route.fulfill(
# Pass all fields from the response.
response=response,
# Override response body.
json=body,
)
def test_disable_fullscreen(
page: Page, app_port: int, assert_snapshot: ImageCompareFunction
):
"""Test that fullscreen mode is disabled for elements when set via host-config."""
page.route(
"**/_stcore/host-config",
handle_route_hostconfig_disable_fullscreen_and_error_dialogs,
)
goto_app(page, f"http://localhost:{app_port}")
# Test that the toolbar is not shown when hovering over a dataframe
dataframe_element = page.get_by_test_id("stDataFrame").nth(0)
dataframe_toolbar = dataframe_element.get_by_test_id("stElementToolbar")
# Hover over dataframe
dataframe_element.hover()
expect(page.get_by_role("button", name="Fullscreen")).not_to_be_attached()
# Check that it is visible (expect waits)
expect(dataframe_toolbar).to_have_css("opacity", "1")
# Take a snapshot
assert_snapshot(
dataframe_toolbar, name="host_config-dataframe_disabled_fullscreen_mode"
)
def test_block_error_dialogs(page: Page, app_port: int):
"""Test that error dialogs are blocked and sent to host when set via host-config."""
# Need to be more specific about the route to allow for successful redirect
page.route(
f"http://localhost:{app_port}/_stcore/host-config",
handle_route_hostconfig_disable_fullscreen_and_error_dialogs,
)
# Initial load of page
goto_app(page, f"http://localhost:{app_port}")
# Capture console messages
messages = []
page.on("console", lambda msg: messages.append(msg))
# Navigate to a non-existent page to trigger page not found error
page.goto(f"http://localhost:{app_port}/nonexistent_page")
# Wait until the expected error is logged - console should include 2 404 errors
# (health & host-config) then the page not found error
wait_until(
page,
lambda: any(
"The page that you have requested does not seem to exist. Running the app's main page."
in message.text
for message in messages
),
)
# Verify no error dialog is shown
expect(page.get_by_role("dialog")).not_to_be_attached()
| 1,152
|
streamlit
|
streamlit/e2e_playwright/hostframe_app.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 time
import streamlit as st
def page2():
st.header("Page 2")
def page3():
st.header("Page 3")
# the multi-pages are added to populate the sidebar. In the test, we are not actually
# use them.
st.navigation(
[
st.Page(page2, title="02_App_Page_2", default=True),
st.Page(page3, title="03_App_Page_3"),
]
)
st.slider("Enter a number", 0, 20, 0)
st.checkbox("Check me out", value=True)
st.radio("Radio Widget", ["Option 1", "Option 2", "Option 3"])
with st.sidebar:
st.write("Hello sidebar")
st.file_uploader("Upload a file")
st.color_picker("Pick a color")
with st.expander("Show URL"):
st.write(f"Full url: {st.context.url}")
st.write("Is app embedded: ", st.context.is_embedded)
st.write(f"Theme type: {st.context.theme.type}")
# Allows for testing of script re-run / stop behavior
time.sleep(3)
| 506
|
streamlit
|
streamlit/e2e_playwright/hostframe_app_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
from typing import Final
import pytest
from playwright.sync_api import FilePayload, FrameLocator, Locator, Route, expect
from e2e_playwright.conftest import (
IframedPage,
IframedPageAttrs,
ImageCompareFunction,
wait_for_app_run,
wait_until,
)
from e2e_playwright.shared.app_utils import (
expect_prefixed_markdown,
get_observed_connection_statuses,
register_connection_status_observer,
)
TEST_ASSETS_DIR: Final[Path] = Path(__file__).parent / "test_assets"
HOSTFRAME_TEST_HTML: Final[str] = (TEST_ASSETS_DIR / "hostframe.html").read_text()
EXPANDER_HEADER_IDENTIFIER = "summary"
HOSTFRAME_TOOLBAR_BUTTON_COUNT = 15
def _load_html_and_get_locators(
iframed_app: IframedPage,
) -> tuple[FrameLocator, Locator]:
page = iframed_app.page
def fulfill_host_config_request(route: Route):
response = route.fetch()
result = response.json()
result["allowedOrigins"] = ["http://localhost"]
route.fulfill(json=result)
page.route("**/_stcore/host-config", fulfill_host_config_request)
frame_locator = iframed_app.open_app(
IframedPageAttrs(html_content=HOSTFRAME_TEST_HTML)
)
# the toolbar and buttons are part of the HTML page, not the iframe
toolbar = page.get_by_test_id("toolbar")
expect(toolbar).to_have_count(1)
toolbar_buttons = toolbar.get_by_role("button")
expect(toolbar_buttons).to_have_count(HOSTFRAME_TOOLBAR_BUTTON_COUNT)
wait_for_app_run(frame_locator)
return frame_locator, toolbar_buttons
def _open_embed(iframed_app: IframedPage) -> FrameLocator:
"""Open the iframe with embed=True and return the frame locator."""
frame_locator: FrameLocator = iframed_app.open_app(
IframedPageAttrs(
src_query_params={"embed": "true"},
)
)
wait_for_app_run(frame_locator)
return frame_locator
def _check_widgets_and_sidebar_nav_links_disabled(frame_locator: FrameLocator):
# Verify that the app's widgets & sidebar nav links are disabled
# Note: checking via .to_be_disabled() only works on native control elements
# (HTML button, input, select, textarea, option, optgroup)
# Other elements (like <label> tags) need to check for a "disabled" attribute instead.
# See https://playwright.dev/python/docs/api/class-locatorassertions#locator-assertions-to-be-disabled
# Slider
slider = frame_locator.get_by_test_id("stSlider")
expect(slider.get_by_test_id("stWidgetLabel")).to_have_attribute("disabled", "")
# Baseweb uses a div with role="slider"
expect(slider.get_by_role("slider")).to_have_attribute("disabled", "")
# Checkbox - widget label disabled if input is disabled
checkbox = frame_locator.get_by_test_id("stCheckbox")
expect(checkbox.get_by_role("checkbox")).to_be_disabled()
# Radio
radio = frame_locator.get_by_test_id("stRadio")
expect(radio.get_by_test_id("stWidgetLabel")).to_have_attribute("disabled", "")
expect(radio.get_by_role("radio").first).to_be_disabled()
# File uploader
file_uploader = frame_locator.get_by_test_id("stFileUploader")
expect(file_uploader.get_by_test_id("stWidgetLabel")).to_have_attribute(
"disabled", ""
)
expect(
file_uploader.get_by_role("button").get_by_text("Browse files")
).to_be_disabled()
# Color picker
color_picker = frame_locator.get_by_test_id("stColorPicker")
expect(color_picker.get_by_test_id("stWidgetLabel")).to_have_attribute(
"disabled", ""
)
# also a div
expect(color_picker.get_by_test_id("stColorPickerBlock")).to_have_attribute(
"disabled", ""
)
# Verify the expander is still active
expander = frame_locator.get_by_test_id("stExpander")
expect(expander).not_to_be_disabled()
expander.click()
expect(expander.get_by_test_id("stExpanderDetails")).to_be_visible()
## Verify that sidebar page nav links are disabled too
sidebar_nav_links = frame_locator.get_by_test_id("stSidebarNavItems").get_by_role(
"link"
)
expect(sidebar_nav_links).to_have_count(2)
expect(sidebar_nav_links.nth(0)).to_have_attribute("disabled", "")
expect(sidebar_nav_links.nth(1)).to_have_attribute("disabled", "")
def test_handles_host_theme_message(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
assert_snapshot(
frame_locator.get_by_test_id("stApp"), name="hostframe_app-theme_message_before"
)
toolbar_buttons.get_by_text("Send Theme").click()
iframed_app.page.wait_for_timeout(5000)
assert_snapshot(
frame_locator.get_by_test_id("stApp"), name="hostframe_app-theme_message_after"
)
def test_handles_set_file_upload_client_config_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
file_name1 = "file1.txt"
file_content1 = b"file1content"
file_name2 = "file2.txt"
file_content2 = b"file2content"
files: list[FilePayload] = [
{"name": file_name1, "mimeType": "text/plain", "buffer": file_content1},
{"name": file_name2, "mimeType": "text/plain", "buffer": file_content2},
]
uploader_index = 0
with iframed_app.page.expect_file_chooser() as fc_info:
frame_locator.get_by_test_id("stFileUploaderDropzone").nth(
uploader_index
).click()
file_chooser = fc_info.value
# First test without file upload config
with iframed_app.page.expect_request(lambda request: request.method == "PUT") as r:
file_chooser.set_files(files=files[0])
url = r.value.url
headers = r.value.all_headers()
response = r.value.response()
assert response is not None
assert response.status == 204 # Upload successful
assert url.startswith("http://localhost")
assert "_stcore/upload_file" in url
assert "header1" not in headers
wait_for_app_run(frame_locator, wait_delay=500)
# Click the button to set the file upload config
toolbar_buttons.get_by_text("Set file upload config").click()
iframed_app.page.wait_for_timeout(5000)
with iframed_app.page.expect_file_chooser() as fc_info:
frame_locator.get_by_test_id("stFileUploaderDropzone").nth(
uploader_index
).click()
file_chooser = fc_info.value
with iframed_app.page.expect_request(lambda request: request.method == "PUT") as r:
file_chooser.set_files(files=files[1])
url = r.value.url
headers = r.value.all_headers()
assert url.startswith("https://some-prefix.com/somethingelse/_stcore/upload_file/")
assert "header1" in headers
assert "header2" in headers
assert headers["header1"] == "header1value"
assert headers["header2"] == "header2value"
def test_set_is_embedded_context_field_embed_true(iframed_app: IframedPage):
frame_locator = _open_embed(iframed_app)
# Check that the context option is set correctly to True
expect_prefixed_markdown(frame_locator, "Is app embedded:", "True")
def test_set_is_embedded_context_field_embed_false(iframed_app: IframedPage):
frame_locator, _ = _load_html_and_get_locators(iframed_app)
# Check that the context option is set correctly to False
expect_prefixed_markdown(frame_locator, "Is app embedded:", "False")
def test_handles_host_rerun_script_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
toolbar_buttons.get_by_text("Rerun Script").click()
expect(frame_locator.get_by_test_id("stApp")).to_have_attribute(
"data-test-script-state", "running"
)
def test_context_url_is_correct_when_hosted_in_iframe(
iframed_app: IframedPage, app_port: int
):
frame_locator, _ = _load_html_and_get_locators(iframed_app)
frame_locator.get_by_test_id("stExpander").locator(
EXPANDER_HEADER_IDENTIFIER
).click()
expect_prefixed_markdown(frame_locator, "Full url:", f"http://localhost:{app_port}")
@pytest.mark.skip(
reason="Skipping this test since we broke this to fix an MPA regression. The plan is to get this running again"
"after we have refactored the dark / light mode support."
)
def test_st_context_theme_respects_dark_theme_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
expect_prefixed_markdown(frame_locator, "Theme type:", "light")
toolbar_buttons.get_by_text("Send Dark Theme").click()
expect_prefixed_markdown(frame_locator, "Theme type:", "dark")
def test_handles_host_stop_script_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
# Make sure script is running
toolbar_buttons.get_by_text("Rerun Script").click()
# Check that status widget is running
expect(frame_locator.get_by_test_id("stApp")).to_have_attribute(
"data-test-script-state", "running"
)
toolbar_buttons.get_by_text("Stop Script").click()
# Check that status widget is no longer running
expect(frame_locator.get_by_test_id("stApp")).to_have_attribute(
"data-test-script-state", "notRunning"
)
def test_handles_host_close_modal_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
# Open the Main Menu
frame_locator.get_by_test_id("stMainMenu").locator("button").click()
# Open the Settings Modal
frame_locator.get_by_test_id("stMainMenuList").get_by_text("Settings").click()
expect(frame_locator.get_by_role("dialog")).to_be_attached()
# Close the Modal
toolbar_buttons.get_by_text("Close Modal").click()
expect(frame_locator.get_by_role("dialog")).not_to_be_attached()
def test_handles_host_menu_item_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
toolbar_buttons.get_by_text("Add Menu Item").click()
# Open the Main Menu
frame_locator.get_by_test_id("stMainMenu").locator("button").click()
menu_list = frame_locator.get_by_test_id("stMainMenuList")
expect(menu_list.get_by_text("Adopt a Corgi")).to_be_attached()
def test_handles_host_toolbar_item_message(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
toolbar_buttons.get_by_text("Add Toolbar Item").click()
toolbar_action_button = frame_locator.get_by_test_id("stToolbarActionButton")
expect(toolbar_action_button).to_have_count(2)
expect(toolbar_action_button.nth(0)).to_have_text("Favorite")
expect(toolbar_action_button.nth(1)).to_have_text("Share")
assert_snapshot(
frame_locator.get_by_test_id("stApp"), name="hostframe_app-toolbar_items"
)
def test_handles_hide_sidebar_nav_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
expect(frame_locator.get_by_test_id("stSidebarNav")).to_be_attached()
toolbar_buttons.get_by_text("Hide Sidebar Nav").click()
expect(frame_locator.get_by_test_id("stSidebarNav")).not_to_be_attached()
def test_handles_sidebar_downshift_message(iframed_app: IframedPage):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
# Trigger sidebar downshift
toolbar_buttons.get_by_text("Sidebar Chevron Downshift").click()
# Hover over sidebar to reveal the button
frame_locator.get_by_test_id("stSidebarContent").hover()
# Close the sidebar
frame_locator.get_by_test_id("stSidebar").locator("button").click()
def test_handles_host_terminate_and_restart_websocket_connection_messages(
iframed_app: IframedPage,
):
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
# Kill the websocket connection and verify that the app moves into an
# error state.
toolbar_buttons.get_by_text("Terminate Websocket").click()
expect(frame_locator.get_by_test_id("stApp")).to_have_attribute(
"data-test-connection-state", "DISCONNECTED_FOREVER"
)
frame = frame_locator.owner.page.frame("guest")
assert frame is not None
# start observing our connection statuses before we click on restart websocket
register_connection_status_observer(frame)
# Request that the websocket connection gets restarted.
toolbar_buttons.get_by_text("Restart Websocket").click()
wait_until(
iframed_app.page,
lambda: len(get_observed_connection_statuses(frame)) == 3,
timeout=5000,
)
statuses = get_observed_connection_statuses(frame)
assert statuses[0] == "PINGING_SERVER"
assert statuses[1] == "CONNECTING"
assert statuses[2] == "CONNECTED"
# Check that the connection state change triggers a rerun of the app.
expect(frame_locator.get_by_test_id("stStatusWidget")).to_be_visible()
expect(frame_locator.get_by_test_id("stApp")).to_have_attribute(
"data-test-script-state", "running"
)
def test_color_picker_closes_without_security_error(iframed_app: IframedPage):
"""
Our color picker component has a bug that causes a security error when
closing the color picker from an iframe with a different origin. See
`BaseColorPicker.tsx` for more details. This test verifies that the color
picker closes without causing a security error in an iframe.
"""
frame_locator, _ = _load_html_and_get_locators(iframed_app)
# Open the color picker, then click somewhere else to close it.
frame_locator.get_by_test_id("stColorPickerBlock").click()
frame_locator.get_by_test_id("stMain").click()
# Wait a bit, then verify no error message is shown in the app.
iframed_app.page.wait_for_timeout(1000)
expect(frame_locator.get_by_test_id("stException")).not_to_be_attached()
def test_handles_set_inputs_disabled_message(iframed_app: IframedPage):
"""
Test verifies that the app handles the set_inputs_disabled message
correctly, by disabling all widgets as well as the sidebar page nav
links.
"""
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
# Trigger the set_inputs_disabled message
toolbar_buttons.get_by_text("Disable Inputs").click()
# Verify that all app's widgets & sidebar page nav links are now disabled
_check_widgets_and_sidebar_nav_links_disabled(frame_locator)
def test_disables_widgets_and_sidebar_page_nav_when_connection_is_lost(
iframed_app: IframedPage,
):
"""
Test verifies that the widgets and the sidebar page nav links are disabled
when the app enters the disconnected state (triggered by terminate websocket).
"""
frame_locator, toolbar_buttons = _load_html_and_get_locators(iframed_app)
frame = frame_locator.owner.page.frame("guest")
assert frame is not None
# start observing our connection statuses before we click on restart websocket
register_connection_status_observer(frame)
# Kill the websocket connection and verify that the app moves into an
# error state.
toolbar_buttons.get_by_text("Terminate Websocket").click()
expect(frame_locator.get_by_test_id("stApp")).to_have_attribute(
"data-test-connection-state", "DISCONNECTED_FOREVER"
)
# Verify that all app's widgets & sidebar page nav links are now disabled
_check_widgets_and_sidebar_nav_links_disabled(frame_locator)
| 6,113
|
streamlit
|
streamlit/e2e_playwright/i18n_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 typing import Any
import pytest
from playwright.sync_api import Page, expect
from e2e_playwright.conftest import ImageCompareFunction
"""
Any tests that should be tested against multiple locales should be placed here.
Because `browser_context_args` is applied by Playwright on the file level, we
should keep only tests that should be run against multiple locales in this file.
See https://playwright.dev/python/docs/test-runners#fixtures for more
information.
"""
@pytest.fixture(params=["en-US", "de-DE", "ja-JP", "ar-EG"])
def browser_context_args(
request: pytest.FixtureRequest,
browser_context_args: dict[str, Any],
) -> dict[str, Any]:
"""
Parameterized fixture that runs for every test function in this module.
Tests against 4 different locales.
"""
locale = request.param
return {
**browser_context_args,
"locale": locale,
}
def test_range_date_calendar_picker_rendering(
app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that the range calendar picker renders correctly via screenshots matching."""
date_input = app.get_by_test_id("stDateInput").first
expect(date_input).to_be_visible()
date_input.scroll_into_view_if_needed()
date_input.click()
calendar_popover = app.locator('[data-baseweb="calendar"]').first
expect(calendar_popover).to_be_visible()
# Add a small timeout to minimize some flakiness:
app.wait_for_timeout(500)
calendar_popover.scroll_into_view_if_needed()
assert_snapshot(
calendar_popover,
name="st_date_input-range_two_dates_calendar",
)
| 725
|
streamlit
|
streamlit/e2e_playwright/iframe_resizer_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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, Final
from playwright.sync_api import FrameLocator, Locator, expect
from e2e_playwright.conftest import IframedPageAttrs, wait_for_app_run
if TYPE_CHECKING:
from collections.abc import Callable
from e2e_playwright.conftest import IframedPage, ImageCompareFunction
from pathlib import Path
TEST_ASSETS_DIR: Final[Path] = Path(__file__).parent / "test_assets"
# we read the iframeResizer script from the assets file and inject the content within a
# <script>{content}</script> tag to the iframe. I wasn't able to load the script from a
# url in the playwright, which is why we do it inline (I also didn't spend a ton of time
# so it might easily be possible).
IFRAME_RESIZER_SCRIPT: Final[str] = (
TEST_ASSETS_DIR / "iframerResizer.min.js"
).read_text()
def _open_with_resize_script(
iframed_app: IframedPage, embed: bool = False, with_min_height: bool = False
) -> FrameLocator:
"""Open the iframe with the resize script and return the frame locator."""
src_query_params = {}
if embed:
src_query_params["embed"] = "true"
frame_locator: FrameLocator = iframed_app.open_app(
IframedPageAttrs(
element_id="exampleframe",
src_query_params=src_query_params,
additional_html_head=f"<script>{IFRAME_RESIZER_SCRIPT}</script>",
)
)
wait_for_app_run(frame_locator)
resize_args: dict[str, str | int] = {"log": "true"}
if with_min_height:
resize_args["minHeight"] = 500
# call the iFrameResize function with the resize arguments
# this will make the iframe resize itself to the content.
# The function is exposed by the injected iframerResizer script.
frame_locator.owner.evaluate(
f"""
() => {{
iFrameResize({resize_args}, '#exampleframe')
}}
""",
)
return frame_locator
def _snapshot_iframe(
iframe: FrameLocator,
action: Callable[[Locator], None] | None,
assert_snapshot: ImageCompareFunction,
snapshot_name: str,
):
slider = iframe.get_by_test_id("stSlider")
expect(slider).to_have_count(1)
expect(slider).to_be_visible()
expect(iframe.get_by_test_id("stMarkdown")).to_have_count(0)
if action:
action(slider)
assert_snapshot(iframe.get_by_test_id("stApp"), name=snapshot_name)
def _snapshot_expanded_iframe(
iframe: FrameLocator,
assert_snapshot: ImageCompareFunction,
snapshot_name: str,
):
def move_slider_and_expect_markdown(slider: Locator):
"""The app renders markdown elements basedf on the slider value."""
slider.hover()
# click in middle of the slider (which should then have the value 10)
slider.click()
wait_for_app_run(iframe)
expect(iframe.get_by_test_id("stMarkdown")).to_have_count(10)
_snapshot_iframe(
iframe,
move_slider_and_expect_markdown,
assert_snapshot,
snapshot_name,
)
def test_render_embedded_iframe_correctly(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
"""Test that the iframe is rendered correctly when embedded
(query param '?embed=true' added to the iframe src url).
"""
frame_locator = _open_with_resize_script(iframed_app, embed=True)
_snapshot_iframe(
frame_locator, None, assert_snapshot, "iframe_resizer-embedded_iframe"
)
def test_render_embedded_iframe_expanded(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
"""Test that the iframe is rendered correctly when embedded
(query param '?embed=true' added to the iframe src url) and
markdown elements rendered.
"""
frame_locator = _open_with_resize_script(iframed_app, embed=True)
_snapshot_expanded_iframe(
frame_locator, assert_snapshot, "iframe_resizer-embedded_iframe_expanded"
)
def test_render_unembedded_iframe_correctly(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
"""Test that the iframe is rendered correctly when not embedded (no
query param added to the iframe src url).
"""
frame_locator = _open_with_resize_script(iframed_app)
_snapshot_iframe(
frame_locator, None, assert_snapshot, "iframe_resizer-unembedded_iframe"
)
def test_render_unembedded_iframe_expanded(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
"""Test that the iframe is rendered correctly when not embedded (no
query param added to the iframe src url) and markdown elements rendered.
"""
frame_locator = _open_with_resize_script(iframed_app)
_snapshot_expanded_iframe(
frame_locator,
assert_snapshot,
"iframe_resizer-unembedded_iframe_expanded",
)
def test_render_unembedded_iframe_with_minheight(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
"""Test that the iframe has a minimum height even if there are no markdown
elements. This means that this screenshot should have a larger height than
the non-expanded, unembedded iframe screenshot without a min-height.
"""
frame_locator = _open_with_resize_script(iframed_app, with_min_height=True)
_snapshot_iframe(
frame_locator,
None,
assert_snapshot,
"iframe_resizer-unembedded_iframe_with_min_height",
)
def test_render_unembedded_iframe_with_minheight_expanded(
iframed_app: IframedPage, assert_snapshot: ImageCompareFunction
):
"""Test that the iframe has a minimum height and expands correctly."""
frame_locator = _open_with_resize_script(iframed_app, with_min_height=True)
_snapshot_expanded_iframe(
frame_locator,
assert_snapshot,
"iframe_resizer-unembedded_iframe_with_min_height_expanded",
)
| 2,395
|
streamlit
|
streamlit/e2e_playwright/lazy_loaded_modules.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 importlib.util
import sys
import streamlit as st
lazy_loaded_modules = [
"altair",
"graphviz",
"matplotlib",
"numpy",
# There is currently a 10% probability that we check for new
# versions on streamlit start-up. This is using the packaging module.
# So, we cannot check this without it being flaky.
# "packaging",
"pandas",
# Pillow is lazy-loaded, but it gets imported by plotly,
# which we have to import in case it is installed to correctly
# configure the Streamlit theme. So, we cannot test this here.
# "PIL",
"pyarrow",
"pydeck",
"rich",
"tenacity",
# toml is automatically loaded if there is a secret.toml, config.toml or
# a local credentials.toml file. So, we cannot test this here.
# Internal modules:
"streamlit.emojis",
"streamlit.external",
"streamlit.material_icon_names",
"streamlit.proto.openmetrics_data_model_pb2",
"streamlit.vendor.pympler",
# Requires `server.fileWatcherType` to be configured with `none` or `poll`:
"watchdog",
"streamlit.watcher.event_based_path_watcher",
]
for module in lazy_loaded_modules:
if module in sys.modules:
label = "imported"
elif importlib.util.find_spec(module) is not None:
label = "not loaded"
else:
label = "not found"
st.write(
f"**{module}**:",
label,
)
if st.button("Import lazy loaded modules"):
for module in lazy_loaded_modules:
__import__(module)
st.rerun()
| 760
|
streamlit
|
streamlit/e2e_playwright/main_menu_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
def test_main_menu_images(themed_app: Page, assert_snapshot: ImageCompareFunction):
themed_app.get_by_test_id("stMainMenu").click()
element = themed_app.get_by_test_id("stMainMenuPopover")
assert_snapshot(element, name="main_menu")
def test_renders_settings_dialog_properly(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
themed_app.get_by_test_id("stMainMenu").click()
themed_app.get_by_text("Settings").click()
dialog = themed_app.get_by_test_id("stDialog")
expect(dialog).to_be_visible()
expect(dialog).to_contain_text("Made with Streamlit")
assert_snapshot(
dialog.get_by_role("dialog"),
name="settings_dialog",
# Hide version info so that snapshots don't change across versions.
style="[data-testid='stVersionInfo'] { display: none !important; }",
)
# Webkit (safari) and firefox doesn't support screencast on linux machines
@pytest.mark.only_browser("chromium")
def test_renders_screencast_dialog_properly(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
themed_app.get_by_test_id("stMainMenu").click()
themed_app.get_by_text("Record a screencast").click()
dialog = themed_app.get_by_test_id("stDialog")
expect(dialog).to_be_visible()
assert_snapshot(dialog.get_by_role("dialog"), name="record_screencast_dialog")
# Webkit (safari) and firefox doesn't support screencast on linux machines
@pytest.mark.only_browser("chromium")
def test_renders_screencast_recorded_dialog_properly(themed_app: Page):
themed_app.get_by_test_id("stMainMenu").click()
themed_app.get_by_text("Record a screencast").click()
themed_app.get_by_text("Start recording!").click()
# Wait 5 seconds because there is a 3! 2! 1! on the screen until recording occurs and there may be buffer
themed_app.wait_for_timeout(5000)
# stop recording
themed_app.keyboard.press("Escape")
dialog = themed_app.get_by_test_id("stDialog")
expect(dialog).to_be_visible()
# don't use screenshot as the recording may differ so just check for specific text
expect(
themed_app.get_by_role("dialog").get_by_text("Preview your video below:")
).to_be_visible()
def test_renders_about_dialog_properly(themed_app: Page):
themed_app.get_by_test_id("stMainMenu").click()
themed_app.get_by_text("About").click()
dialog = themed_app.get_by_test_id("stDialog")
expect(dialog).to_be_visible()
expect(dialog).to_contain_text("This can be markdown!")
def test_renders_clear_cache_dialog_properly(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
themed_app.get_by_test_id("stMainMenu").click()
themed_app.get_by_text("Clear cache").click()
dialog = themed_app.get_by_test_id("stDialog")
expect(dialog).to_be_visible()
expect(dialog).to_contain_text(
"Are you sure you want to clear the app's function caches?"
)
assert_snapshot(dialog.get_by_role("dialog"), name="clear_cache_dialog")
| 1,312
|
streamlit
|
streamlit/e2e_playwright/markdown_features.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 datetime
import numpy as np
import streamlit as st
markdown_table = """
| Syntax | Description |
| ----------- | ----------- |
| Header | Title |
| Paragraph | Text |
"""
ordered_list = """
1. First Item
2. Second Item
"""
unordered_list = """
- Item 1
- Item 2
"""
task_list = """
- [x] Write the press release
- [ ] Update the website
- [ ] Contact the media
"""
horizontal_rule = """
Horizontal Rule:
---
"""
MARKDOWN_FEATURES = {
"Normal": "Normal Text",
"Bold": "**Bold Text**",
"Italic": "*Italicized*",
"Strikethrough": "~Strikethough~",
"Code": "`Code Block`",
"Emoji": "Emoji: 🐶",
"Emoji shortcode": ":joy:",
"Arrows & dashes": "<- -> <-> -- >= <= ~=",
"Material Icon": "Icon: :material/check_circle:",
"Streamlit Logo": "Logo: :streamlit:",
"Image": "",
"Colored Text": ":red[Colored] :rainbow[Text]",
"Colored Background": ":blue-background[Colored] :red-background[Background]",
"Badge": ":blue-badge[Badge] :red-badge[Badge]",
"Latex": "$ax^2 + bx + c = 0$",
"Link": "[Link](https://streamlit.io)",
"Blockquote": "> Testing Blockquote",
"Heading 1": "# Heading 1",
"Heading 2": "## Heading 2",
"Table": markdown_table,
"Ordered list": ordered_list,
"Unordered list": unordered_list,
"Task list": task_list,
"Horizontal rule": horizontal_rule,
}
selected_feature = st.radio("Markdown Features", list(MARKDOWN_FEATURES.keys()))
selected_feature_markdown = MARKDOWN_FEATURES[selected_feature]
st.header("Text Elements", divider=True)
st.container(key="st_write").write(selected_feature_markdown)
st.container(key="st_markdown").markdown(selected_feature_markdown)
st.container(key="st_title").title(selected_feature_markdown)
st.container(key="st_header").header(selected_feature_markdown)
st.container(key="st_subheader").subheader(selected_feature_markdown)
st.container(key="st_caption").caption(selected_feature_markdown)
st.container(key="st_success").success(selected_feature_markdown)
st.container(key="st_error").error(selected_feature_markdown)
st.container(key="st_warning").warning(selected_feature_markdown)
st.container(key="st_info").info(selected_feature_markdown)
st.header("Widgets", divider=True)
st.container(key="st_checkbox").checkbox(selected_feature_markdown)
st.container(key="st_toggle").toggle(selected_feature_markdown)
st.container(key="st_radio_widget_label").radio(
selected_feature_markdown, ["Option 1", "Option 2"]
)
st.container(key="st_radio_option_label").radio(
"Option Label Test", [selected_feature_markdown, "Option 2"]
)
st.container(key="st_selectbox").selectbox(
selected_feature_markdown,
["Option 1", "Option 2"],
)
st.container(key="st_multiselect").multiselect(
selected_feature_markdown, ["Blue", "Purple"]
)
st.container(key="st_slider").slider(selected_feature_markdown, 0, 10, 1)
st.container(key="st_select_slider").select_slider(
selected_feature_markdown, ["Blue", "Purple"]
)
st.container(key="st_select_slider_min_label").select_slider(
"Select slider min label",
options=["min", "max"],
value="max",
format_func=lambda option: (
selected_feature_markdown if option == "min" else "Plain Option"
),
)
st.container(key="st_select_slider_max_label").select_slider(
"Select slider max label",
options=["min", "max"],
value="min",
format_func=lambda option: (
selected_feature_markdown if option == "max" else "Plain Option"
),
)
st.container(key="st_select_slider_value").select_slider(
"Select slider current value",
options=["min", "value", "max"],
value="value",
format_func=lambda option: (
selected_feature_markdown if option == "value" else "Plain Option"
),
)
st.container(key="st_text_input").text_input(selected_feature_markdown)
st.container(key="st_number_input").number_input(selected_feature_markdown)
st.container(key="st_text_area").text_area(selected_feature_markdown)
st.container(key="st_date_input").date_input(
selected_feature_markdown, datetime.date(2000, 3, 7)
)
st.container(key="st_time_input").time_input(
selected_feature_markdown, datetime.time(8, 45)
)
st.container(key="st_file_uploader").file_uploader(selected_feature_markdown)
st.container(key="st_color_picker").color_picker(selected_feature_markdown)
st.container(key="st_audio_input").audio_input(selected_feature_markdown)
st.header("Button-like Elements", divider=True)
st.container(key="st_button").button(selected_feature_markdown)
st.container(key="st_download_button").download_button(
selected_feature_markdown, "Text"
)
st.container(key="st_link_button").link_button(
selected_feature_markdown, "https://streamlit.io"
)
st.container(key="st_popover").popover(selected_feature_markdown).write("Expanded!")
st.container(key="st_pills_widget_label").pills(selected_feature_markdown, ["Option 1"])
st.container(key="st_pills_button_label").pills(
"Button Label Test", [selected_feature_markdown]
)
st.container(key="st_segmented_control_widget_label").segmented_control(
selected_feature_markdown, ["Option 1"]
)
st.container(key="st_segmented_control_button_label").segmented_control(
"Button Label Test", [selected_feature_markdown]
)
st.container(key="st_page_link").page_link(
"https://streamlit.io", label=selected_feature_markdown
)
st.header("Containers", divider=True)
st.container(key="st_expander").expander(selected_feature_markdown).write("Expanded!")
st.container(key="st_tabs").tabs([selected_feature_markdown])
st.header("Other Elements", divider=True)
st.container(key="st_metric").metric(selected_feature_markdown, value=7, delta=0.5)
st.container(key="st_metric_value").metric(
label="Metric with markdown value", value=selected_feature_markdown, delta=0.5
)
st.container(key="st_metric_delta").metric(
label="Metric with markdown delta", value=7, delta=selected_feature_markdown
)
st.container(key="st_image").image(
np.repeat(0, 10000).reshape(100, 100), caption=selected_feature_markdown
)
st.container(key="st_progress").progress(0.5, selected_feature_markdown)
st.container(key="st_table").table(
{
"Header": [selected_feature_markdown],
}
)
@st.dialog(selected_feature_markdown)
def test_dialog():
st.image(
np.repeat(0, 10000).reshape(100, 100)
) # element that doesn't support markdown
# Add dialog test - we need to create a button to trigger it
# and the dialog will be tested when opened
if st.container(key="st_dialog").button("Open Dialog"):
test_dialog()
| 2,570
|
streamlit
|
streamlit/e2e_playwright/markdown_features_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 re
from typing import TYPE_CHECKING
from playwright.sync_api import Locator, Page, expect
from e2e_playwright.shared.app_utils import get_element_by_key, select_radio_option
if TYPE_CHECKING:
from collections.abc import Callable
# List of markdown features that are not allowed in (widget) labels:
DISALLOWED_FEATURES_IN_LABEL: list[str] = [
"Blockquote",
"Heading 1",
"Heading 2",
"Table",
"Ordered list",
"Unordered list",
"Task list",
"Horizontal rule",
]
DISALLOWED_FEATURES_IN_HEADINGS: list[str] = ["Blockquote", "Table"]
# List of markdown features that are not allowed in button-like elements:
DISALLOWED_FEATURES_IN_BUTTONS: list[str] = [*DISALLOWED_FEATURES_IN_LABEL, "Link"]
# Mapping between a feature and the supported markdown features:
DISALLOWED_MARKDOWN_FEATURES: dict[str, list[str]] = {
"st_write": [],
"st_markdown": [],
"st_caption": [],
"st_success": [],
"st_error": [],
"st_warning": [],
"st_info": [],
"st_title": [*DISALLOWED_FEATURES_IN_HEADINGS, "Heading 2"],
"st_header": [*DISALLOWED_FEATURES_IN_HEADINGS, "Heading 1"],
"st_subheader": [*DISALLOWED_FEATURES_IN_HEADINGS, "Heading 1", "Heading 2"],
"st_checkbox": DISALLOWED_FEATURES_IN_LABEL,
"st_toggle": DISALLOWED_FEATURES_IN_LABEL,
"st_radio_widget_label": DISALLOWED_FEATURES_IN_LABEL,
"st_radio_option_label": DISALLOWED_FEATURES_IN_LABEL,
"st_selectbox": DISALLOWED_FEATURES_IN_LABEL,
"st_multiselect": DISALLOWED_FEATURES_IN_LABEL,
"st_slider": DISALLOWED_FEATURES_IN_LABEL,
"st_select_slider": DISALLOWED_FEATURES_IN_LABEL,
"st_select_slider_min_label": DISALLOWED_FEATURES_IN_LABEL,
"st_select_slider_max_label": DISALLOWED_FEATURES_IN_LABEL,
"st_select_slider_value": DISALLOWED_FEATURES_IN_LABEL,
"st_text_input": DISALLOWED_FEATURES_IN_LABEL,
"st_number_input": DISALLOWED_FEATURES_IN_LABEL,
"st_text_area": DISALLOWED_FEATURES_IN_LABEL,
"st_date_input": DISALLOWED_FEATURES_IN_LABEL,
"st_time_input": DISALLOWED_FEATURES_IN_LABEL,
"st_file_uploader": DISALLOWED_FEATURES_IN_LABEL,
"st_color_picker": DISALLOWED_FEATURES_IN_LABEL,
"st_audio_input": DISALLOWED_FEATURES_IN_LABEL,
"st_button": DISALLOWED_FEATURES_IN_BUTTONS,
"st_download_button": DISALLOWED_FEATURES_IN_BUTTONS,
"st_link_button": DISALLOWED_FEATURES_IN_BUTTONS,
"st_popover": DISALLOWED_FEATURES_IN_BUTTONS,
"st_pills_button_label": DISALLOWED_FEATURES_IN_BUTTONS,
"st_pills_widget_label": DISALLOWED_FEATURES_IN_LABEL,
"st_segmented_control_button_label": DISALLOWED_FEATURES_IN_BUTTONS,
"st_segmented_control_widget_label": DISALLOWED_FEATURES_IN_LABEL,
"st_page_link": DISALLOWED_FEATURES_IN_BUTTONS,
"st_expander": DISALLOWED_FEATURES_IN_LABEL,
"st_tabs": DISALLOWED_FEATURES_IN_LABEL,
"st_metric": DISALLOWED_FEATURES_IN_LABEL,
"st_metric_value": DISALLOWED_FEATURES_IN_LABEL,
"st_metric_delta": DISALLOWED_FEATURES_IN_LABEL,
"st_image": DISALLOWED_FEATURES_IN_LABEL,
"st_progress": DISALLOWED_FEATURES_IN_LABEL,
"st_table": [],
"st_dialog": DISALLOWED_FEATURES_IN_LABEL,
}
# Mapping between a markdown feature and the playwright locator to detect the feature:
MARKDOWN_FEATURE_PLAYWRIGHT_LOCATORS: dict[str, Callable[[Locator], Locator]] = {
"Bold": lambda locator: locator.locator("strong"),
"Italic": lambda locator: locator.locator("em"),
"Strikethrough": lambda locator: locator.locator("del"),
"Code": lambda locator: locator.locator("code"),
"Emoji": lambda locator: locator.get_by_text("🐶"),
"Emoji shortcode": lambda locator: locator.get_by_text("😂"),
"Arrows & dashes": lambda locator: locator.get_by_text("← → ↔ — ≥ ≤ ≈"),
"Material Icon": lambda locator: locator.locator("span").get_by_text(
"check_circle"
),
"Streamlit Logo": lambda locator: locator.locator("img"),
"Image": lambda locator: locator.locator("img"),
"Colored Text": lambda locator: locator.locator("span"),
"Colored Background": lambda locator: locator.locator("span"),
"Badge": lambda locator: locator.locator("span"),
"Latex": lambda locator: locator.locator("span.katex"),
"Link": lambda locator: locator.locator("a"),
"Blockquote": lambda locator: locator.locator("blockquote"),
"Heading 1": lambda locator: locator.locator("h1"),
"Heading 2": lambda locator: locator.locator("h2"),
"Table": lambda locator: locator.locator("table"),
"Ordered list": lambda locator: locator.locator("ol"),
"Unordered list": lambda locator: locator.locator("ul"),
"Task list": lambda locator: locator.locator("ul.contains-task-list"),
"Horizontal rule": lambda locator: locator.locator("hr"),
}
def test_markdown_restrictions_for_all_elements(app: Page):
"""Test that markdown restrictions are correctly applied to all elements."""
# Iterate through all markdown features
for feature, locator_fn in MARKDOWN_FEATURE_PLAYWRIGHT_LOCATORS.items():
# Select the current markdown feature
select_radio_option(app, re.compile(f"^{feature}$"), label="Markdown Features")
# Test the feature against all Streamlit elements
for element_name, disallowed_features in DISALLOWED_MARKDOWN_FEATURES.items():
# Get the container for the current element
container = get_element_by_key(app, element_name)
expect(container).to_be_visible()
if element_name == "st_dialog":
# Click the button to open the dialog
button = container.get_by_role("button", name="Open Dialog")
button.click()
# Set the container to the dialog so we can test the markdown
container = app.get_by_test_id("stDialog")
expect(container).to_be_visible()
markdown_container_test_id = "stMarkdownContainer"
# st.caption and st.image caption uses a different container
if element_name in ["st_caption", "st_image"]:
markdown_container_test_id = "stCaptionContainer"
element_locator = locator_fn(
container.get_by_test_id(markdown_container_test_id)
)
if feature in disallowed_features:
# Feature should not be present
expect(element_locator.first).not_to_be_attached()
else:
# Feature should be present
expect(element_locator.first).to_be_visible()
if element_name == "st_dialog":
# Close the dialog
app.keyboard.press("Escape")
expect(container).not_to_be_visible()
| 3,004
|
streamlit
|
streamlit/e2e_playwright/mega_tester_app.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 random
import time
from pathlib import Path
from typing import Literal, cast
import altair as alt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import pydeck as pdk
import streamlit as st
TEST_ASSETS_DIR = Path(__file__).parent / "test_assets"
np.random.seed(42)
random.seed(42)
LOREM = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor "
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation "
"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit "
"in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
def generate_sparkline_data(
length: int = 15, drift: float = 0.05, 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 cast("list[float]", data.tolist())
# Add disable toggle in sidebar
with st.sidebar:
help_text = "Tooltip text" if st.toggle("Show tooltips", True) else None
disabled = st.toggle("Disable widgets", False)
nav_sections = st.toggle("Page sections", True)
many_pages = st.toggle("Many pages", False)
top_nav = st.toggle("Top navigation", False)
wide_mode = st.toggle("Wide mode", False)
st.divider()
STREAMLIT_LOGO_SMALL_PATH = TEST_ASSETS_DIR / "streamlit-logo-small.png"
st.logo(
STREAMLIT_LOGO_SMALL_PATH
if STREAMLIT_LOGO_SMALL_PATH.is_file()
else "https://streamlit.io/images/brand/streamlit-mark-color.png",
size="small",
)
st.title("🎈 Mega tester app")
st.set_page_config("Mega tester app", "🎈", layout="wide" if wide_mode else "centered")
def page1():
pass
def page2():
pass
def page3():
pass
def page4():
pass
def page5():
pass
def page6():
pass
def page7():
pass
def page8():
pass
def page9():
pass
def page10():
pass
def page11():
pass
def page12():
pass
def page13():
pass
if many_pages:
pages = {
"General": [
st.Page(page1, title="Home", icon=":material/home:"),
st.Page(page2, title="Data visualizations", icon=":material/monitoring:"),
st.Page(page3, title="Analytics", icon=":material/analytics:"),
],
"Tools": [
st.Page(page4, title="Calculator", icon=":material/calculate:"),
st.Page(page5, title="Editor", icon=":material/edit:"),
st.Page(page6, title="Viewer", icon=":material/visibility:"),
st.Page(page7, title="Converter", icon=":material/swap_horiz:"),
],
"Data": [
st.Page(page8, title="Import", icon=":material/file_upload:"),
st.Page(page9, title="Export", icon=":material/file_download:"),
st.Page(page10, title="Transform", icon=":material/transform:"),
],
"Admin": [
st.Page(page11, title="Settings", icon=":material/settings:"),
st.Page(page12, title="Users", icon=":material/people:"),
st.Page(page13, title="Logs", icon=":material/history:"),
],
}
else:
pages = {
"General": [
st.Page(page1, title="Home", icon=":material/home:"),
st.Page(page2, title="Data visualizations", icon=":material/monitoring:"),
],
"Admin": [st.Page(page3, title="Settings", icon=":material/settings:")],
}
st.navigation(
pages if nav_sections else [page for section in pages.values() for page in section],
position="top" if top_nav else "sidebar",
)
"## Write and magic"
st.write("st.write")
"magic"
"## Text elements"
st.markdown("st.markdown", help=help_text)
st.markdown(
"Markdown features: **bold** *italic* ~strikethrough~ [link](https://streamlit.io) `code` $a=b$ 🐶 :cat: "
":material/home: :streamlit: <- -> <-> -- >= <= ~= :small[small] $$a = b$$"
)
st.markdown("""
Text colors:
:blue[blue] :green[green] :orange[orange] :red[red] :violet[violet] :gray[gray] :rainbow[rainbow] :primary[primary]
:blue-background[blue] :green-background[green] :orange-background[orange] :red-background[red]
:violet-background[violet] :gray-background[gray] :rainbow-background[rainbow] :primary-background[primary]
:blue-badge[blue] :green-badge[green] :orange-badge[orange] :red-badge[red] :violet-badge[violet]
:gray-badge[gray] :primary-badge[primary]
""")
st.title("st.title", help=help_text)
st.header("st.header", help=help_text)
st.header("st.header with blue divider", divider="blue", help=help_text)
st.header("st.header with green divider", divider="green", help=help_text)
st.header("st.header with yellow divider", divider="yellow", help=help_text)
st.header("st.header with orange divider", divider="orange", help=help_text)
st.header("st.header with red divider", divider="red", help=help_text)
st.header("st.header with violet divider", divider="violet", help=help_text)
st.header("st.header with gray divider", divider="gray", help=help_text)
st.header("st.header with rainbow divider", divider="rainbow", help=help_text)
st.subheader("st.subheader", help=help_text)
st.badge("st.badge", icon=":material/home:", color="green")
st.caption("st.caption", help=help_text)
st.code("# st.code\na = 1234")
st.code("# st.code with line numbers\na = 1234", line_numbers=True)
st.code(
'# st.code with line wrapping\na = "This is a very very very very very very very very very '
'very very very long string"',
wrap_lines=True,
)
with st.echo():
st.write("st.echo")
st.latex(r"\int a x^2 \,dx", help=help_text)
st.text("st.text", help=help_text)
st.divider()
"## Data elements"
data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
"st.dataframe"
st.dataframe(data)
"st.dataframe with selections"
event_data = st.dataframe(
data, on_select="rerun", selection_mode=["multi-row", "multi-column", "multi-cell"]
)
st.write("Your dataframe selection is", event_data["selection"])
"st.data_editor"
st.data_editor(data, num_rows="dynamic", disabled=disabled)
"st.column_config"
data_df = pd.DataFrame(
{
"column": ["foo", "bar", "baz"],
"text": ["foo", "bar", "baz"],
"number": [1, 2, 3],
"checkbox": [True, False, True],
"selectbox": ["foo", "bar", "foo"],
"datetime": pd.to_datetime(
["2021-01-01 00:00:00", "2021-01-02 00:00:00", "2021-01-03 00:00:00"]
),
"date": pd.to_datetime(["2021-01-01", "2021-01-02", "2021-01-03"]),
"time": pd.to_datetime(["00:00:00", "01:00:00", "02:00:00"]),
"list": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
"link": [
"https://streamlit.io",
"https://streamlit.io",
"https://streamlit.io",
],
"image": [
"https://picsum.photos/200/300",
"https://picsum.photos/200/300",
"https://picsum.photos/200/300",
],
"area_chart": [[1, 2, 1], [2, 3, 1], [3, 1, 2]],
"line_chart": [[1, 2, 1], [2, 3, 1], [3, 1, 2]],
"bar_chart": [[1, 2, 1], [2, 3, 1], [3, 1, 2]],
"progress": [0.1, 0.2, 0.3],
"json": [
{
"foo": "bar",
},
{
"numbers": [123, 4.56],
},
{
"level1": {"level2": {"level3": {"a": "b"}}},
},
],
}
)
st.data_editor(
data_df,
column_config={
"column": st.column_config.Column(
"Column", help="A column tooltip", pinned=True
),
"text": st.column_config.TextColumn("TextColumn"),
"number": st.column_config.NumberColumn("NumberColumn"),
"checkbox": st.column_config.CheckboxColumn("CheckboxColumn"),
"selectbox": st.column_config.SelectboxColumn(
"SelectboxColumn", options=["foo", "bar", "baz"]
),
"datetime": st.column_config.DatetimeColumn("DatetimeColumn"),
"date": st.column_config.DateColumn("DateColumn"),
"time": st.column_config.TimeColumn("TimeColumn"),
"list": st.column_config.ListColumn("ListColumn"),
"link": st.column_config.LinkColumn("LinkColumn"),
"image": st.column_config.ImageColumn("ImageColumn"),
"area_chart": st.column_config.AreaChartColumn("AreaChartColumn"),
"line_chart": st.column_config.LineChartColumn("LineChartColumn"),
"bar_chart": st.column_config.BarChartColumn("BarChartColumn"),
"progress": st.column_config.ProgressColumn("ProgressColumn"),
"json": st.column_config.JsonColumn("JSONColumn"),
},
)
"st.table"
st.table(data.iloc[0:5])
col1, col2, col3 = st.columns(3)
col1.metric("st.metric positive", 1234, 123, help=help_text)
col2.metric("st.metric negative", 1234, -123, help=help_text)
col3.metric("st.metric neutral", 1234, 123, delta_color="off", help=help_text)
col1, col2, col3 = st.columns(3)
col1.metric(
"st.metric positive",
1234,
123,
border=True,
help=help_text,
chart_data=generate_sparkline_data(),
chart_type="line",
)
col2.metric(
"st.metric negative",
1234,
-123,
border=True,
help=help_text,
chart_data=generate_sparkline_data(),
chart_type="area",
)
col3.metric(
"st.metric neutral",
1234,
123,
border=True,
help=help_text,
chart_data=generate_sparkline_data(),
chart_type="bar",
delta_color="off",
)
"st.json"
st.json(
{
"foo": "bar",
"numbers": [
123,
4.56,
],
"level1": {"level2": {"level3": {"a": "b"}}},
},
expanded=2,
)
"## Chart elements"
more_lines = st.toggle("Show more lines", False)
data = pd.DataFrame(
np.random.randn(20, 10 if more_lines else 3),
columns=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
if more_lines
else ["a", "b", "c"],
)
"st.area_chart"
stack = cast(
"Literal['normalize', 'center'] | bool",
st.segmented_control(
"stack",
[True, False, "normalize", "center"],
key="area_chart_stack",
),
)
st.area_chart(data, x_label="x label", y_label="y label", stack=stack)
"st.bar_chart"
horizontal = st.toggle("horizontal", False)
stack = cast(
"Literal['normalize', 'center'] | bool",
st.segmented_control(
"stack",
[True, False, "normalize", "center"],
key="bar_chart_stack",
),
)
st.bar_chart(
data, x_label="x label", y_label="y label", horizontal=horizontal, stack=stack
)
"st.line_chart"
st.line_chart(data, x_label="x label", y_label="y label")
"st.scatter_chart"
st.scatter_chart(data, x_label="x label", y_label="y label")
"st.map"
df = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=["lat", "lon"]
)
st.map(df)
"st.pyplot"
fig, ax = plt.subplots()
ax.hist(data, bins=20)
st.pyplot(fig)
"st.altair_chart"
st.altair_chart(
alt.Chart(data)
.mark_circle()
.encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"]),
use_container_width=True,
)
"st.vega_lite_chart"
st.vega_lite_chart(
data,
{
"mark": {"type": "circle", "tooltip": True},
"encoding": {
"x": {"field": "a", "type": "quantitative"},
"y": {"field": "b", "type": "quantitative"},
"size": {"field": "c", "type": "quantitative"},
"color": {"field": "c", "type": "quantitative"},
},
},
use_container_width=True,
)
"st.plotly_chart"
df = px.data.gapminder()
fig = px.scatter(
df.query("year==2007"),
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
hover_name="country",
log_x=True,
size_max=60,
)
st.plotly_chart(fig, use_container_width=True)
"st.pydeck_chart"
data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=["lat", "lon"]
)
st.pydeck_chart(
pdk.Deck(
map_style=None,
initial_view_state=pdk.ViewState(
latitude=37.76,
longitude=-122.4,
zoom=11,
pitch=50,
),
layers=[
pdk.Layer(
"HexagonLayer",
data=data,
get_position="[lon, lat]",
radius=200,
elevation_scale=4,
elevation_range=[0, 1000],
pickable=True,
extruded=True,
),
pdk.Layer(
"ScatterplotLayer",
data=data,
get_position="[lon, lat]",
get_color="[200, 30, 0, 160]",
get_radius=200,
),
],
)
)
"st.graphviz_chart"
st.graphviz_chart(
"""
digraph {
run -> intr
intr -> runbl
runbl -> run
run -> kernel
kernel -> zombie
kernel -> sleep
kernel -> runmem
sleep -> swap
swap -> runswap
runswap -> new
runswap -> runmem
new -> runmem
sleep -> runmem
}
"""
)
"## Input widgets"
if st.button("st.button", help=help_text, icon=":material/home:", disabled=disabled):
st.write("You pressed the button!")
if st.button(
"st.button primary",
type="primary",
help=help_text,
icon=":material/home:",
disabled=disabled,
):
st.write("You pressed the button!")
if st.button(
"st.button tertiary",
type="tertiary",
help=help_text,
icon=":material/home:",
disabled=disabled,
):
st.write("You pressed the button!")
st.download_button(
"st.download_button",
data="Hello!",
icon=":material/home:",
help=help_text,
disabled=disabled,
)
"st.feedback"
st.feedback("thumbs", disabled=disabled)
st.feedback("faces", disabled=disabled)
st.feedback("stars", disabled=disabled)
st.link_button(
"st.link_button",
"https://streamlit.io",
icon=":material/home:",
help=help_text,
disabled=disabled,
)
st.page_link(
"https://streamlit.io",
label="st.page_link",
icon=":material/home:",
help=help_text,
disabled=disabled,
)
checkbox_input = st.checkbox("st.checkbox", True, help=help_text, disabled=disabled)
st.write(f"Your checkbox input is {checkbox_input}!")
toggle_input = st.toggle("st.toggle", True, help=help_text, disabled=disabled)
st.write(f"Your toggle input is {toggle_input}!")
radio_input = st.radio("st.radio", ["cat", "dog"], help=help_text, disabled=disabled)
st.write(f"Your radio input is {radio_input}!")
radio_input = st.radio(
"st.radio horizontal",
["cat", "dog"],
horizontal=True,
help=help_text,
disabled=disabled,
)
st.write(f"Your radio input is {radio_input}!")
accept_new_options = st.toggle("accept new options")
selectbox_input = st.selectbox(
"st.selectbox",
["cat", "dog", "monkey", "snake", "bird"],
accept_new_options=accept_new_options,
help=help_text,
disabled=disabled,
)
st.write(f"Your selectbox input is {selectbox_input}!")
multiselect_input = st.multiselect(
"st.multiselect",
["cat", "dog", "monkey", "snake", "bird"],
default=["cat", "monkey"],
accept_new_options=accept_new_options,
disabled=disabled,
help=help_text,
)
st.write(f"Your multiselect input is {multiselect_input}!")
pills_input = st.pills(
"st.pills",
["cat", "dog", "monkey", "snake", "bird"],
selection_mode="multi",
default=["cat", "monkey"],
disabled=disabled,
help=help_text,
)
st.write(f"Your pills input is {pills_input}!")
segmented_control_input = st.segmented_control(
"st.segmented_control",
["cat", "dog", "monkey", "snake", "bird"],
selection_mode="multi",
default=["cat", "monkey"],
disabled=disabled,
help=help_text,
)
st.write(f"Your segmented control input is {segmented_control_input}!")
color_input = st.color_picker("st.color_picker", disabled=disabled, help=help_text)
st.write(f"Your color input hex is {color_input}!")
number_input = st.number_input("st.number_input", disabled=disabled, help=help_text)
st.write(f"Your number input is {number_input}!")
range_sliders = st.toggle("Range sliders", False)
slider_input = st.slider(
"st.slider",
value=[30, 60] if range_sliders else 30,
disabled=disabled,
help=help_text,
)
st.write(f"Your slider input is {slider_input}!")
select_slider_input = st.select_slider(
"st.select_slider",
options=["xsmall", "small", "medium", "large", "xlarge"],
value=["small", "large"] if range_sliders else "small",
disabled=disabled,
help=help_text,
)
st.write(f"Your select_slider input is {select_slider_input}!")
date_input = st.date_input("st.date_input", disabled=disabled, help=help_text)
st.write(f"Your date input is {date_input}!")
time_input = st.time_input("st.time_input", disabled=disabled, help=help_text)
st.write(f"Your time input is {time_input}!")
text_input = st.text_input("st.text_input", disabled=disabled, help=help_text)
st.write(f"Your text input is {text_input}!")
text_area_input = st.text_area("st.text_area", disabled=disabled, help=help_text)
st.write(f"Your text_area input is {text_area_input}!")
audio_input = st.audio_input("st.audio_input", disabled=disabled, help=help_text)
st.write(f"Your audio input is {audio_input}!")
accept_multiple_files = st.segmented_control(
"accept_multiple_files", [False, True, "directory"], default=False
)
uploaded_file = st.file_uploader(
"st.file_uploader",
type=["png", "jpg"],
accept_multiple_files=accept_multiple_files, # type: ignore
disabled=disabled,
help=help_text,
)
st.write(f"Your uploaded file is {uploaded_file}!")
if st.toggle("Show camera input (requires camera permission)", False):
cam_input = st.camera_input("st.camera_input", disabled=disabled, help=help_text)
st.write(f"Your cam input is {cam_input}!")
"## Media elements"
"st.image"
EXAMPLE_IMAGE_PATH = TEST_ASSETS_DIR / "streamlit-logo.png"
st.image(
EXAMPLE_IMAGE_PATH
if EXAMPLE_IMAGE_PATH.is_file()
else "https://picsum.photos/200/300"
)
"st.audio"
EXAMPLE_AUDIO_PATH = TEST_ASSETS_DIR / "cat-purr.mp3"
st.audio(
EXAMPLE_AUDIO_PATH
if EXAMPLE_AUDIO_PATH.is_file()
else "https://file-examples.com/storage/fef6248bef689f7bb9c274f/2017/11/file_example_MP3_700KB.mp3"
)
"st.video"
EXAMPLE_VIDEO_PATH = TEST_ASSETS_DIR / "flower.webm"
st.video(
EXAMPLE_VIDEO_PATH
if EXAMPLE_VIDEO_PATH.is_file()
else "https://file-examples.com/storage/fef6248bef689f7bb9c274f/2017/04/file_example_MP4_480_1_5MG.mp4"
)
"st.pdf"
# TODO: st.pdf is not compatible with the current CSP / iframe configuration
# within our tests:
show_pdf = st.toggle("Show pdf", False)
if show_pdf:
EXAMPLE_PDF_PATH = TEST_ASSETS_DIR / "sample.pdf"
st.pdf(
EXAMPLE_PDF_PATH
if EXAMPLE_PDF_PATH.is_file()
else "https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf"
)
"## Layouts and containers"
"st.columns"
a, b = st.columns(2)
a.write("column 1")
b.write("column 2")
"st.columns with border"
a, b = st.columns(2, border=True)
a.write("column 1")
b.write("column 2")
st.container().write("st.container")
st.container(border=True).write("st.container with border")
width = cast(
"Literal['small', 'medium', 'large']",
st.segmented_control(
"st.dialog width", ["small", "medium", "large"], default="small"
),
)
dismissible = st.toggle("st.dialog dismissible", True)
@st.dialog("Test dialog", width=width, dismissible=dismissible)
def dialog():
st.write("Hello there!")
st.write(LOREM)
if st.button("Close", disabled=disabled):
st.rerun()
if st.button("Open st.dialog"):
dialog()
a = st.empty()
a.write("st.empty")
with st.expander("st.expander"):
st.write("works!")
with st.popover("st.popover", disabled=disabled, help=help_text):
st.write("works!")
st.sidebar.write("st.sidebar")
with st.sidebar:
st.selectbox(
"st.selectbox sidebar",
["cat", "dog", "monkey", "snake", "bird"],
disabled=disabled,
)
st.button("st.button sidebar", disabled=disabled)
st.checkbox("st.checkbox sidebar", True, disabled=disabled)
st.info("st.info sidebar")
st.expander("st.expander sidebar").write("works!")
"st.tabs"
tab_a, tab_b = st.tabs(["tab 1", "tab 2"])
tab_b.write("tab 1 content")
tab_a.write("tab 2 content")
"## Chat elements"
"st.chat_input"
if st.toggle("Show chat input at the bottom of the screen", False):
st.chat_input(accept_file="multiple", disabled=disabled)
else:
st.container().chat_input(accept_file="multiple", disabled=disabled)
"st.chat_message"
st.chat_message("assistant").write("Hello there!")
if st.button("Start st.status"):
with st.status("Working on it...", expanded=True) as status:
time.sleep(1)
st.write("Some content...")
time.sleep(1)
st.write("Some content...")
time.sleep(1)
st.write("Some content...")
status.update(label="Done!", state="complete")
if st.button("Start st.write_stream"):
def stream():
for i in ["hello", " streaming", " world"]:
time.sleep(0.5)
yield i
st.write_stream(stream)
"## Status elements"
if st.button("st.progress"):
my_bar = st.progress(0)
for percent_complete in range(100):
my_bar.progress(percent_complete + 1)
time.sleep(0.05)
if st.button("st.spinner"):
with st.spinner("Wait!", show_time=True):
time.sleep(3)
st.write("spinner works if you saw it!")
duration = st.segmented_control(
"duration", ["short", "long", "infinite"], default="short"
)
if st.button("st.toast"):
st.toast("Hello there!", icon="🎈", duration=duration) # type: ignore[arg-type]
if st.button("st.balloons"):
st.balloons()
if st.button("st.snow"):
st.snow()
st.success("st.success")
st.success("st.success with icon", icon=":material/home:")
st.info("st.info")
st.info("st.info with icon", icon=":material/home:")
st.warning("st.warning")
st.warning("st.warning with icon", icon=":material/home:")
st.error("st.error")
st.error("st.error with icon", icon=":material/home:")
st.exception(RuntimeError("st.exception"))
"## Execution flow"
"st.fragment"
@st.fragment
def my_fragment():
if st.button("Wait 1s inside the fragment"):
time.sleep(1)
my_fragment()
if st.button("st.rerun"):
st.rerun()
if st.button("st.stop"):
st.stop()
st.write("if you see this, st.stop does not work") # type: ignore[unreachable]
with st.form(key="tester"):
"st.form"
text_tester = st.text_input("Your text", disabled=disabled, help=help_text)
st.form_submit_button("Submit", disabled=disabled, help=help_text)
st.write("Your text is:", text_tester)
st.write("## Utilities")
"st.help"
st.help(st.write)
st.write("## State Management")
"st.session_state"
if "foo" not in st.session_state:
st.session_state["foo"] = "bar"
st.write(st.session_state)
if st.button("Add st.query_params"):
st.query_params["foo"] = "bar"
"st.context.cookies"
st.write(st.context.cookies)
"st.context.headers"
st.write(st.context.headers)
"st.context.ip_address"
st.write(st.context.ip_address)
"st.context.is_embedded"
st.write(st.context.is_embedded)
"st.context.locale"
st.write(st.context.locale)
"st.context.theme.type"
st.write(st.context.theme.type)
"st.context.timezone"
st.write(st.context.timezone)
"st.context.timezone_offset"
st.write(st.context.timezone_offset)
"st.context.url"
st.write(st.context.url)
| 10,460
|
streamlit
|
streamlit/e2e_playwright/mega_tester_app_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 re
from typing import TYPE_CHECKING
import pytest
from playwright.sync_api import expect
from e2e_playwright.conftest import IframedPage, rerun_app, wait_for_app_run
from e2e_playwright.shared.app_utils import expect_no_skeletons, goto_app
if TYPE_CHECKING:
from playwright.sync_api import ConsoleMessage, FrameLocator, Page
def is_expected_error(
msg: ConsoleMessage, browser_name: str, *, uses_csp: bool
) -> bool:
# Mapbox error is expected and should be ignored:
if (
msg.text == "Failed to load resource: net::ERR_CONNECTION_REFUSED"
and "events.mapbox.com" in msg.location["url"]
):
return True
# There is an expected error with pydeck and firefox related to WebGL rendering
# This seems to be an issue with firefox used with playwright:
if re.search(r"deck:.*is null undefined", msg.text) and browser_name == "firefox":
return True
# TODO(lukasmasuch): Investigate why firefox is running into this eval issue:
if (
(
"settings blocked a JavaScript eval (script-src) from being executed"
in msg.text
)
and browser_name == "firefox"
and uses_csp
):
return True
# TODO(lukasmasuch): Investigate why webkit is running into this blob: issue:
return bool(
msg.text == "Failed to load resource"
and "blob:http://localhost:" in msg.location["url"]
and browser_name == "webkit"
and uses_csp
)
def test_no_console_errors(page: Page, app_port: int, browser_name: str):
"""Test that the app does not log any console errors."""
console_errors = []
def on_console_message(msg: ConsoleMessage) -> None:
# Possible message types: "log", "debug", "info", "error", "warning", ...
if msg.type == "error" and not is_expected_error(
msg, browser_name, uses_csp=False
):
# Each console message has text, location, etc.
console_errors.append(
{
"message": msg.text,
"url": msg.location["url"],
"line": msg.location["lineNumber"],
"column": msg.location["columnNumber"],
}
)
page.on("console", on_console_message)
goto_app(page, f"http://localhost:{app_port}")
page.wait_for_load_state()
# Make sure that all elements are rendered and no skeletons are shown:
expect_no_skeletons(page, timeout=25000)
# There should be only one exception in the app:
expect(page.get_by_test_id("stException")).to_have_count(1)
# Check that title is visible:
expect(page.get_by_text("🎈 Mega tester app")).to_be_visible()
# There should be no unexpected console errors:
assert not console_errors, "Console errors were logged " + str(console_errors)
def test_mega_tester_app_in_iframe(iframed_app: IframedPage, browser_name: str):
"""Test that the mega tester app can be loaded within an iframe with CSP."""
console_errors = []
def on_console_message(msg: ConsoleMessage) -> None:
# Possible message types: "log", "debug", "info", "error", "warning", ...
if msg.type == "error" and not is_expected_error(
msg, browser_name, uses_csp=True
):
# Each console message has text, location, etc.
console_errors.append(
{
"message": msg.text,
"url": msg.location["url"],
"line": msg.location["lineNumber"],
"column": msg.location["columnNumber"],
}
)
page: Page = iframed_app.page
page.on("console", on_console_message)
frame_locator: FrameLocator = iframed_app.open_app(None)
wait_for_app_run(frame_locator)
page.wait_for_load_state()
# Make sure that all elements are rendered and no skeletons are shown:
expect_no_skeletons(frame_locator, timeout=25000)
# Check that title is visible:
expect(frame_locator.get_by_text("🎈 Mega tester app")).to_be_visible()
# There should be only one exception in the app:
expect(frame_locator.get_by_test_id("stException")).to_have_count(1)
# Check that there are no dialogs (e.g. with errors) visible:
expect(frame_locator.get_by_test_id("stDialog")).to_have_count(0)
# There should be no unexpected console errors:
assert not console_errors, "Console errors were logged " + str(console_errors)
@pytest.mark.performance
@pytest.mark.repeat(5) # only repeat 5 times since otherwise it would take too long
def test_mega_tester_app_rendering_performance(app: Page):
"""Test the performance of the mega tester app rendering."""
# Rerun the app 5 times:
for _ in range(5):
rerun_app(app)
| 2,107
|
streamlit
|
streamlit/e2e_playwright/multipage_apps/mpa_basics.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
import streamlit as st
st.header("Main Page")
st.slider("x")
st.write("Query Params:", st.query_params)
if st.button("`pages/02_page2.py`"):
st.switch_page("pages/02_page2.py")
if st.button("`pages/08_slow_page.py`"):
st.switch_page(Path("pages/08_slow_page.py"))
| 297
|
streamlit
|
streamlit/e2e_playwright/multipage_apps/mpa_basics_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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_loaded,
wait_for_app_run,
)
from e2e_playwright.shared.app_utils import (
click_button,
get_button_group,
get_segment_button,
goto_app,
wait_for_all_images_to_be_loaded,
)
from e2e_playwright.shared.react18_utils import take_stable_snapshot
def test_loads_main_script_on_initial_page_load(app: Page):
"""Test that the main script is loaded on initial page load."""
expect(app.get_by_test_id("stHeading")).to_contain_text("Main Page")
def test_renders_sidebar_nav_correctly(
themed_app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that the sidebar nav is rendered correctly."""
assert_snapshot(themed_app.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav")
def test_can_switch_between_pages_by_clicking_on_sidebar_links(app: Page):
"""Test that we can switch between pages by clicking on sidebar links."""
app.get_by_test_id("stSidebarNav").locator("a").nth(1).click()
wait_for_app_run(app)
expect(app.get_by_test_id("stHeading")).to_contain_text("Page 2")
def test_supports_navigating_to_page_directly_via_url(page: Page, app_port: int):
"""Test that we can navigate to a page directly via URL."""
goto_app(page, f"http://localhost:{app_port}/page2")
expect(page.get_by_test_id("stHeading")).to_contain_text("Page 2")
def test_can_switch_between_pages_and_edit_widgets(app: Page):
"""Test that we can switch between pages and edit widgets."""
slider = app.get_by_test_id("stSlider").locator('[role="slider"]')
expect(slider).to_be_visible()
slider.click()
slider.press("ArrowRight")
wait_for_app_run(app, wait_delay=500)
sidebar_nav_link = app.get_by_test_id("stSidebarNav").locator("a").nth(2)
expect(sidebar_nav_link).to_be_visible()
sidebar_nav_link.click()
wait_for_app_run(app, wait_delay=2000)
expect(app.get_by_role("heading", name="Page 3")).to_be_visible()
expect(app.get_by_test_id("stHeading")).to_contain_text("Page 3")
expect(app.get_by_test_id("stMarkdown")).to_contain_text("x is 0")
expect(slider).to_be_visible()
slider.click()
slider.press("ArrowRight")
wait_for_app_run(app)
expect(app.get_by_test_id("stMarkdown")).to_contain_text("x is 1")
def test_can_switch_to_the_first_page_with_a_duplicate_name(app: Page):
"""Test that we can switch to the first page with a duplicate name."""
app.get_by_test_id("stSidebarNav").locator("a").nth(3).click()
wait_for_app_run(app)
expect(app.get_by_test_id("stHeading")).to_contain_text("Page 4")
def test_runs_the_first_page_with_a_duplicate_name_if_navigating_via_url(
page: Page, app_port: int
):
"""Test that we run the first page with a duplicate name if navigating via URL."""
goto_app(page, f"http://localhost:{app_port}/page_with_duplicate_name")
expect(page.get_by_test_id("stHeading")).to_contain_text("Page 4")
def test_show_not_found_dialog(page: Page, app_port: int):
"""Test that we show a not found dialog if the page doesn't exist."""
goto_app(page, f"http://localhost:{app_port}/not_a_page")
expect(page.locator('[role="dialog"]')).to_contain_text("Page not found")
def test_handles_expand_collapse_of_mpa_nav_correctly(
page: Page, app_port: int, assert_snapshot: ImageCompareFunction
):
"""Test that we handle expand/collapse of MPA nav correctly."""
goto_app(page, f"http://localhost:{app_port}/page_7")
view_button = page.get_by_test_id("stSidebarNavViewButton")
expect(view_button).to_be_visible()
# Expand the nav
view_button.click(force=True)
# We apply a quick timeout here so that the UI has some time to
# adjust for the screenshot after the click
page.wait_for_timeout(250)
# move the mouse out of the way to avoid hover effects
page.mouse.move(0, 0)
assert_snapshot(
page.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav_expanded"
)
# Collapse the nav
view_button.click(force=True)
page.wait_for_timeout(250)
# move the mouse out of the way to avoid hover effects
page.mouse.move(0, 0)
assert_snapshot(
page.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav_collapsed"
)
# Expand the nav again
view_button.click(force=True)
page.wait_for_timeout(250)
# move the mouse out of the way to avoid hover effects
page.mouse.move(0, 0)
assert_snapshot(
page.get_by_test_id("stSidebarNav"), name="mpa-sidebar_nav_expanded"
)
def test_switch_page(app: Page):
"""Test that we can switch between pages by triggering st.switch_page."""
# Click the button to trigger st.switch_page using relative path
app.get_by_test_id("stButton").nth(0).locator("button").first.click()
wait_for_app_run(app)
# Check that we are on the correct page
expect(app.get_by_test_id("stHeading")).to_contain_text("Page 2")
# st.switch_page using relative path & leading /
click_button(app, "pages/06_page_6.py")
expect(app.get_by_test_id("stHeading")).to_contain_text("Page 6")
# st.switch_page using relative path & leading ./
click_button(app, "./mpa_basics.py")
expect(app.get_by_test_id("stHeading")).to_contain_text("Main Page")
def test_switch_page_preserves_embed_params(page: Page, app_port: int):
"""Test that st.switch_page only preserves embed params."""
# Start at main page with embed & other query params
goto_app(
page,
f"http://localhost:{app_port}/?embed=true&embed_options=light_theme&bar=foo",
)
expect(page.get_by_test_id("stJson")).to_contain_text('{"bar":"foo"}')
# Trigger st.switch_page
page.get_by_test_id("stButton").nth(0).locator("button").first.click()
wait_for_app_loaded(page)
# Check that only embed query params persist
expect(page).to_have_url(
f"http://localhost:{app_port}/page2?embed=true&embed_options=light_theme"
)
expect(page.get_by_test_id("stJson")).not_to_contain_text('{"bar":"foo"}')
def test_switch_page_removes_query_params(page: Page, app_port: int):
"""Test that query params are removed when navigating via st.switch_page."""
# Start at main page with query params
goto_app(page, f"http://localhost:{app_port}/?foo=bar")
# Trigger st.switch_page
page.get_by_test_id("stButton").nth(0).locator("button").first.click()
wait_for_app_loaded(page)
# Check that query params don't persist
expect(page).to_have_url(f"http://localhost:{app_port}/page2")
def test_switch_page_switches_immediately_if_second_page_is_slow(app: Page):
app.get_by_test_id("stButton").nth(1).locator("button").first.click()
# Wait for the view container and main menu to appear (like in wait_for_app_loaded),
# but don't wait for the script to finish running.
app.wait_for_selector(
"[data-testid='stAppViewContainer']", timeout=30000, state="attached"
)
app.wait_for_selector("[data-testid='stMainMenu']", timeout=20000, state="attached")
# We expect to see the page transition to the slow page by the time this call times
# out in 5s. Otherwise, the page contents aren't being rendered until the script has
# fully completed, and we've run into https://github.com/streamlit/streamlit/issues/7954
expect(app.get_by_test_id("stHeading")).to_contain_text("Slow page")
def test_widget_state_reset_on_page_switch(app: Page):
# Regression test for GH issue 7338
# Page 3
app.get_by_test_id("stSidebarNav").locator("a").nth(2).click()
expect(app.get_by_role("heading", name="Page 3")).to_be_visible()
slider = app.locator('.stSlider [role="slider"]')
slider.click()
slider.press("ArrowRight")
wait_for_app_run(app, wait_delay=500)
expect(app.get_by_test_id("stMarkdown")).to_contain_text("x is 1")
# Switch to the slow page
app.get_by_test_id("stSidebarNav").locator("a").nth(7).click()
expect(app.get_by_role("heading", name="slow page")).to_be_visible()
# Wait for the view container and main menu to appear (like in wait_for_app_loaded),
# but don't wait for the script to finish running.
app.wait_for_selector(
"[data-testid='stAppViewContainer']", timeout=30000, state="attached"
)
app.wait_for_selector("[data-testid='stMainMenu']", timeout=20000, state="attached")
# Back to page 3
app.get_by_test_id("stSidebarNav").locator("a").nth(2).click()
expect(app.get_by_role("heading", name="Page 3")).to_be_visible()
wait_for_app_run(app, wait_delay=500)
# Slider reset
expect(app.get_by_test_id("stMarkdown")).to_contain_text("x is 0")
def test_removes_query_params_when_swapping_pages(page: Page, app_port: int):
"""Test that query params are removed when swapping pages."""
goto_app(page, f"http://localhost:{app_port}/page_7?foo=bar")
page.get_by_test_id("stSidebarNav").locator("a").nth(2).click()
wait_for_app_loaded(page)
expect(page).to_have_url(f"http://localhost:{app_port}/page3")
def test_removes_non_embed_query_params_when_swapping_pages(page: Page, app_port: int):
"""Test that query params are removed when swapping pages."""
goto_app(
page,
f"http://localhost:{app_port}/page_7?foo=bar&embed=True&embed_options=show_toolbar&embed_options=show_colored_line",
)
page.get_by_test_id("stSidebarNav").locator("a").nth(2).click()
wait_for_app_loaded(page)
expect(page).to_have_url(
f"http://localhost:{app_port}/page3?embed=true&embed_options=show_toolbar&embed_options=show_colored_line"
)
def test_renders_logos(app: Page, assert_snapshot: ImageCompareFunction):
"""Test that logos display properly in sidebar and main sections."""
# Go to logo page & wait short moment for logo to appear
app.get_by_test_id("stSidebarNav").locator("a").nth(8).click()
wait_for_app_loaded(app)
expect(app.get_by_role("heading", name="Logo page")).to_be_visible()
# Sidebar logo
expect(app.get_by_test_id("stSidebarHeader").locator("a")).to_have_attribute(
"href", "https://www.example.com"
)
wait_for_all_images_to_be_loaded(app)
take_stable_snapshot(
app,
app.get_by_test_id("stSidebar"),
assert_snapshot,
name="sidebar-logo",
)
# Collapse the sidebar
app.get_by_test_id("stSidebarContent").hover()
collapse_button = app.get_by_test_id("stSidebarCollapseButton").locator("button")
expect(collapse_button).to_be_visible()
collapse_button.click()
app.wait_for_timeout(1000)
# Wait for sidebar to be collapsed, the expand button should now be visible in the header
expect(app.get_by_test_id("stExpandSidebarButton")).to_be_visible()
# Collapsed logo should be in the header
header_element = app.get_by_test_id("stHeader")
logo_link_element = header_element.get_by_test_id("stLogoLink")
expect(logo_link_element).to_be_visible()
expect(logo_link_element).to_have_attribute("href", "https://www.example.com")
collapsed_logo_image = logo_link_element.get_by_test_id("stHeaderLogo")
expect(collapsed_logo_image).to_be_visible()
wait_for_all_images_to_be_loaded(app)
take_stable_snapshot(
app,
collapsed_logo_image,
assert_snapshot,
name="collapsed-header-logo",
)
def test_renders_small_logos(app: Page, assert_snapshot: ImageCompareFunction):
"""Test that small logos display properly in sidebar and main sections."""
# Go to small logo page & wait short moment for logo to appear
app.get_by_test_id("stSidebarNav").locator("a").nth(9).click()
wait_for_app_loaded(app)
expect(app.get_by_role("heading", name="Logo page")).to_be_visible()
# Sidebar logo
expect(app.get_by_test_id("stSidebarHeader").locator("a")).to_have_attribute(
"href", "https://www.example.com"
)
assert_snapshot(app.get_by_test_id("stSidebar"), name="small-sidebar-logo")
def test_renders_large_logos(app: Page, assert_snapshot: ImageCompareFunction):
"""Test that large logos display properly in sidebar and main sections."""
# Go to large logo page & wait short moment for logo to appear
app.get_by_test_id("stSidebarNav").locator("a").nth(10).click()
wait_for_app_loaded(app)
expect(app.get_by_role("heading", name="Logo page")).to_be_visible()
# Sidebar logo
expect(app.get_by_test_id("stSidebarHeader").locator("a")).to_have_attribute(
"href", "https://www.example.com"
)
wait_for_all_images_to_be_loaded(app)
take_stable_snapshot(
app,
app.get_by_test_id("stSidebar"),
assert_snapshot,
name="large-sidebar-logo",
)
# Collapse the sidebar
app.get_by_test_id("stSidebarContent").hover()
collapse_button = app.get_by_test_id("stSidebarCollapseButton").locator("button")
expect(collapse_button).to_be_visible()
collapse_button.click()
app.wait_for_timeout(1000)
# Wait for sidebar to be collapsed, the expand button should now be visible in the header
expect(app.get_by_test_id("stExpandSidebarButton")).to_be_visible()
# Collapsed logo should be in the header
header_element = app.get_by_test_id("stHeader")
logo_link_element = header_element.get_by_test_id("stLogoLink")
expect(logo_link_element).to_be_visible()
expect(logo_link_element).to_have_attribute("href", "https://www.example.com")
collapsed_logo_image = logo_link_element.get_by_test_id("stHeaderLogo")
expect(collapsed_logo_image).to_be_visible()
wait_for_all_images_to_be_loaded(app)
take_stable_snapshot(
app,
collapsed_logo_image,
assert_snapshot,
name="large-collapsed-header-logo",
)
def test_completes_script_lifecycle(app: Page):
app.get_by_test_id("stSidebarNav").locator("a").nth(11).click()
wait_for_app_loaded(app)
# Verify initial state is set correctly
expect(app.get_by_text("radio value: A, state value: A")).to_be_visible()
# Update the radio button and verify the state is updated
radio_button = app.get_by_test_id("stRadio").first
radio_option = radio_button.locator('label[data-baseweb="radio"]').nth(1)
radio_option.click(delay=50)
wait_for_app_run(app)
expect(app.get_by_text("radio value: B, state value: B")).to_be_visible()
# Switch the segmented control to remove the radio button
segmented_control = get_button_group(app, "layout_mode")
get_segment_button(segmented_control, "layout2").click()
wait_for_app_run(app)
# Switch back to the layout with the radio button
get_segment_button(segmented_control, "layout1").click()
wait_for_app_run(app)
# Expect the state to be reset to the initial state
expect(app.get_by_text("radio value: A, state value: A")).to_be_visible()
| 5,965
|
streamlit
|
streamlit/e2e_playwright/multipage_apps/mpa_configure_sidebar_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 get_element_by_key
@pytest.fixture(scope="module")
@pytest.mark.early
def configure_show_sidebar_nav():
"""Configure client.showSidebarNavigation=False."""
# We need to do this in a package scope fixture to ensure that its applied
# before the app server is started.
os.environ["STREAMLIT_CLIENT_SHOW_SIDEBAR_NAVIGATION"] = "False"
yield
del os.environ["STREAMLIT_CLIENT_SHOW_SIDEBAR_NAVIGATION"]
@pytest.mark.usefixtures("configure_show_sidebar_nav")
def test_hides_sidebar_nav(app: Page):
"""Test that client.showSidebarNavigation=False hides the sidebar."""
expect(app.get_by_test_id("stSidebar")).not_to_be_attached()
@pytest.mark.usefixtures("configure_show_sidebar_nav")
def test_page_links_in_main(themed_app: Page, assert_snapshot: ImageCompareFunction):
"""Test that page link appears as expected in main."""
expect(themed_app.get_by_test_id("stSidebar")).not_to_be_attached()
page_links = themed_app.get_by_test_id("stPageLink-NavLink")
expect(page_links).to_have_count(4)
# Selected page
assert_snapshot(page_links.nth(0), name="current-page-link")
page_links.nth(0).hover()
assert_snapshot(page_links.nth(0), name="current-page-link-hover")
# Non-selected page
assert_snapshot(page_links.nth(1), name="page-link")
page_links.nth(1).hover()
assert_snapshot(page_links.nth(1), name="page-link-hover")
# Disabled page
assert_snapshot(page_links.nth(2), name="page-link-disabled")
@pytest.mark.usefixtures("configure_show_sidebar_nav")
def test_page_links_use_correct_margin(
app: Page, assert_snapshot: ImageCompareFunction
):
"""Test that page links use the correct margin."""
page_link_container = get_element_by_key(app, "page_link_container")
assert_snapshot(page_link_container, name="st_page_link-correct_margin")
# Firefox seems to be a bit flaky here, it seems that sometimes the
# sidebar with the nav items is still shown.
@pytest.mark.skip_browser("firefox")
@pytest.mark.usefixtures("configure_show_sidebar_nav")
def test_page_links_in_sidebar(themed_app: Page, assert_snapshot: ImageCompareFunction):
"""Test that page link appears as expected in sidebar."""
page_links = themed_app.get_by_test_id("stPageLink-NavLink")
# Navigate to Page 4
page_links.nth(3).click()
wait_for_app_run(themed_app)
page_links = themed_app.get_by_test_id("stPageLink-NavLink")
expect(page_links).to_have_count(4)
# Selected page
assert_snapshot(page_links.nth(3), name="current-page-link-sidebar")
page_links.nth(3).hover()
assert_snapshot(page_links.nth(3), name="current-page-link-sidebar-hover")
# Non-selected page
assert_snapshot(page_links.nth(0), name="page-link-sidebar")
page_links.nth(0).hover()
assert_snapshot(page_links.nth(0), name="page-link-sidebar-hover")
# Disabled page
assert_snapshot(page_links.nth(2), name="page-link-sidebar-disabled")
@pytest.mark.usefixtures("configure_show_sidebar_nav")
def test_page_link_href(app: Page):
"""Test that page link href set properly."""
page_links = app.get_by_test_id("stPageLink-NavLink")
expect(page_links.nth(0)).to_have_attribute("href", "")
expect(page_links.nth(1)).to_have_attribute("href", "page2")
expect(page_links.nth(2)).to_have_attribute("href", "page3")
expect(page_links.nth(3)).to_have_attribute("href", "page_with_duplicate_name")
# Firefox seems to be a bit flaky here, it seems that sometimes the
# sidebar with the nav items is still shown.
@pytest.mark.skip_browser("firefox")
@pytest.mark.usefixtures("configure_show_sidebar_nav")
def test_logo_no_sidebar(app: Page, assert_snapshot: ImageCompareFunction):
"""Test that logo renders properly with no sidebar."""
expect(app.get_by_test_id("stSidebar")).not_to_be_attached()
# Even with no sidebar, the logo should appear in the header area.
# The stExpandSidebarButton should NOT be visible as there's no sidebar to expand.
expect(app.get_by_test_id("stExpandSidebarButton")).not_to_be_visible()
header_element = app.get_by_test_id("stHeader")
logo_link_element = header_element.get_by_test_id("stLogoLink")
expect(logo_link_element).to_be_visible()
expect(logo_link_element).to_have_attribute("href", "https://www.example.com")
header_logo_image = logo_link_element.get_by_test_id("stHeaderLogo")
expect(header_logo_image).to_be_visible()
assert_snapshot(header_logo_image, name="header-logo-no-sidebar")
| 1,916
|
streamlit
|
streamlit/e2e_playwright/multipage_apps/mpa_v2_custom_theme.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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.header("📊 Random App Content")
st.radio("**Example Main Content**", ["Home", "About", "Contact"])
st.slider("**Example Slider**", 0, 100, 50)
st.divider()
with st.sidebar:
st.subheader("Having fun yet?")
st.slider("Amount of fun", 0, 1000, 450)
pg = st.navigation(
{
"Overview": [
st.Page(
"pages/02_page2.py",
title="Home Page",
default=True,
icon=":material/home:",
),
st.Page(
"pages/03_page3.py", title="Plant Page", icon=":material/potted_plant:"
),
],
"Random": [
st.Page("pages/09_logo_page.py", title="Logo Page", icon=":material/star:"),
st.Page(
"pages/06_page_6.py",
title="Star Page",
icon=":material/star_border:",
),
st.Page(
"pages/07_page_7.py",
title="Animal Page",
icon=":material/pets:",
),
st.Page(
"pages/08_slow_page.py",
title="Random Page",
icon=":material/rocket_launch:",
),
st.Page(
"pages/04_page_with_duplicate_name.py",
title="Time Page",
icon=":material/access_time:",
),
st.Page(
"pages/06_page_6.py",
title="Events Page",
url_path="events",
icon=":material/emoji_events:",
),
],
}
)
pg.run()
st.write("End of Main Page")
| 1,130
|
streamlit
|
streamlit/e2e_playwright/multipage_apps/mpa_v2_custom_theme_test.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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, wait_for_app_loaded
@pytest.fixture(scope="module")
@pytest.mark.early
def configure_custom_text_color():
"""Configure theme.textColor and theme.primaryColor."""
# We need to do this in a package scope fixture to ensure that its applied
# before the app server is started.
os.environ["STREAMLIT_THEME_TEXT_COLOR"] = "#BB1010"
os.environ["STREAMLIT_THEME_PRIMARY_COLOR"] = "#0E0E0E"
yield
del os.environ["STREAMLIT_THEME_TEXT_COLOR"]
del os.environ["STREAMLIT_THEME_PRIMARY_COLOR"]
@pytest.mark.usefixtures("configure_custom_text_color")
def test_custom_text_color(app: Page, assert_snapshot: ImageCompareFunction):
"""Test that custom text color is applied correctly to SidebarNav."""
app.get_by_text("Logo Page").click()
wait_for_app_loaded(app)
assert_snapshot(app.get_by_test_id("stSidebar"), name="sidebar-nav-custom-theme")
| 537
|
streamlit
|
streamlit/e2e_playwright/multipage_apps/pages/09_logo_page.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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 pathlib
from PIL import Image
import streamlit as st
small_logo = Image.open(
str(pathlib.Path(__file__).parent.parent / "small-streamlit.png")
)
logo = Image.open(str(pathlib.Path(__file__).parent.parent / "full-streamlit.png"))
st.header("Logo page")
st.logo(logo, link="https://www.example.com", icon_image=small_logo)
with st.sidebar:
st.radio("Example Sidebar Content", ["Home", "About", "Contact"])
| 329
|
streamlit
|
streamlit/e2e_playwright/multipage_apps_v2/mpa_v2_anchors.py
|
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025)
#
# 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
def page1():
st.title("Page1")
st.write("""
Instructions:
* Click the button below.
* A new tab will open (that's OK)
* The app in that tab should scroll down to 'My title 2'
""")
st.link_button("Open new tab", "/page2#my-title-2")
def page2():
st.title("Page2")
st.header("My title 1")
for _ in range(30):
st.text("blah " * 100)
st.header("My title 2")
for _ in range(30):
st.text("blah " * 100)
page = st.navigation(
[
st.Page(page1, title="Page1"),
st.Page(page2, title="Page2"),
]
)
page.run()
| 456
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.