-
Notifications
You must be signed in to change notification settings - Fork 255
Add test setup for each component #68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sfc-gh-pbelczyk
merged 23 commits into
master
from
STREAMLIT-3894-duplicate-e2e-setup-for-all-examples-and-components
Aug 22, 2023
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
47b0550
Add simple test case for each component
sfc-gh-pbelczyk 2d9f23f
Remove page.pause() from all tests
sfc-gh-pbelczyk 470c668
Fix template tests
sfc-gh-pbelczyk d24ae2a
Update cookiecutter template
sfc-gh-pbelczyk 9a4d682
Update cookie cutter template
sfc-gh-pbelczyk ebfae49
Sync cookie cutter templates
sfc-gh-pbelczyk 753f3f4
Rename frontend-react/build to frontend/build
sfc-gh-pbelczyk 1ffc66b
Try to fail test on pipeline
sfc-gh-pbelczyk b1a94de
Run tests with pip install
sfc-gh-pbelczyk 7e0dc45
Add --yes flag to pip install
sfc-gh-pbelczyk c3435bb
Move --yes flag to correct command
sfc-gh-pbelczyk 7e55753
Last index for paths
sfc-gh-pbelczyk 33b9531
print my_component.__file__
sfc-gh-pbelczyk 93c5059
Run template test with pyenv
sfc-gh-pbelczyk b9a291a
Check e2e tests on pipeline
sfc-gh-pbelczyk fa2a3c5
Destroy template reactless test
sfc-gh-pbelczyk 9b59552
One more test
sfc-gh-pbelczyk 5e99e14
Check if test fail on pipeline
sfc-gh-pbelczyk 6b565d1
Check on pipeline
sfc-gh-pbelczyk 4cabd3f
Cleanup python script
sfc-gh-pbelczyk 0528ad2
Revert example of template-reactless
sfc-gh-pbelczyk fd9b48e
Update template tests
sfc-gh-pbelczyk 4ef22f4
Update docs
sfc-gh-pbelczyk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
cookiecutter/{{ cookiecutter.package_name }}/e2e/e2e_utils.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import contextlib | ||
| import logging | ||
| import os | ||
| import shlex | ||
| import socket | ||
| import subprocess | ||
| import sys | ||
| import time | ||
| import typing | ||
| from contextlib import closing | ||
| from tempfile import TemporaryFile | ||
|
|
||
| import requests | ||
|
|
||
|
|
||
| LOGGER = logging.getLogger(__file__) | ||
|
|
||
|
|
||
| def _find_free_port(): | ||
| with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: | ||
| s.bind(("", 0)) # 0 means that the OS chooses a random port | ||
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| return int(s.getsockname()[1]) # [1] contains the randomly selected port number | ||
|
|
||
|
|
||
| class AsyncSubprocess: | ||
| """A context manager. Wraps subprocess. Popen to capture output safely.""" | ||
|
|
||
| def __init__(self, args, cwd=None, env=None): | ||
| self.args = args | ||
| self.cwd = cwd | ||
| self.env = env | ||
| self._proc = None | ||
| self._stdout_file = None | ||
|
|
||
| def terminate(self): | ||
| """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.start() | ||
| return self | ||
|
|
||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| self.stop() | ||
|
|
||
| def start(self): | ||
| # 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+") | ||
| LOGGER.info("Running command: %s", 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} if self.env else None, | ||
| ) | ||
|
|
||
| def stop(self): | ||
| 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 | ||
|
|
||
|
|
||
| class StreamlitRunner: | ||
| def __init__( | ||
| self, script_path: os.PathLike, server_port: typing.Optional[int] = None | ||
| ): | ||
| self._process = None | ||
| self.server_port = server_port | ||
| self.script_path = script_path | ||
|
|
||
| def __enter__(self): | ||
| self.start() | ||
| return self | ||
|
|
||
| def __exit__(self, type, value, traceback): | ||
| self.stop() | ||
|
|
||
| def start(self): | ||
| self.server_port = self.server_port or _find_free_port() | ||
| self._process = AsyncSubprocess( | ||
| [ | ||
| sys.executable, | ||
| "-m", | ||
| "streamlit", | ||
| "run", | ||
| str(self.script_path), | ||
| f"--server.port={self.server_port}", | ||
| "--server.headless=true", | ||
| "--browser.gatherUsageStats=false", | ||
| "--global.developmentMode=false", | ||
| ] | ||
| ) | ||
| self._process.start() | ||
| if not self.is_server_running(): | ||
| self._process.stop() | ||
| raise RuntimeError("Application failed to start") | ||
|
|
||
| def stop(self): | ||
| self._process.stop() | ||
|
|
||
| def is_server_running(self, timeout: int = 30): | ||
| with requests.Session() as http_session: | ||
| start_time = time.time() | ||
| print("Start loop: ", start_time) | ||
| while True: | ||
| with contextlib.suppress(requests.RequestException): | ||
| response = http_session.get(self.server_url + "/_stcore/health") | ||
| if response.text == "ok": | ||
| return True | ||
| time.sleep(3) | ||
| if time.time() - start_time > 60 * timeout: | ||
| return False | ||
|
|
||
| @property | ||
| def server_url(self): | ||
| if not self.server_port: | ||
| raise RuntimeError("Unknown server port") | ||
| return f"http://localhost:{self.server_port}" | ||
34 changes: 34 additions & 0 deletions
34
cookiecutter/{{ cookiecutter.package_name }}/e2e/test_template.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from playwright.sync_api import Page, expect | ||
|
|
||
| from e2e_utils import StreamlitRunner | ||
|
|
||
| ROOT_DIRECTORY = Path(__file__).parent.parent.absolute() | ||
| BASIC_EXAMPLE_FILE = ROOT_DIRECTORY / "my_component" / "example.py" | ||
|
|
||
| @pytest.fixture(autouse=True, scope="module") | ||
| def streamlit_app(): | ||
| with StreamlitRunner(BASIC_EXAMPLE_FILE) as runner: | ||
| yield runner | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True, scope="function") | ||
| def go_to_app(page: Page, streamlit_app: StreamlitRunner): | ||
| page.goto(streamlit_app.server_url) | ||
| # Wait for app to load | ||
| page.get_by_role("img", name="Running...").is_hidden() | ||
|
|
||
|
|
||
| def test_should_render_template(page: Page): | ||
| frame = page.frame_locator( | ||
| 'iframe[title="my_component\\.my_component"] >> nth=0' | ||
| ) | ||
|
|
||
| expect(page.get_by_text("You've clicked 0 times!").first).to_be_visible() | ||
|
|
||
| frame.get_by_role("button", name="Click me!").click() | ||
|
|
||
| expect(page.get_by_text("You've clicked 1 times!").first).to_be_visible() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
cookiecutter/{{ cookiecutter.package_name }}/{{ cookiecutter.import_name }}/example.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import streamlit as st | ||
| from {{ cookiecutter.import_name }} import {{ cookiecutter.import_name }} | ||
|
|
||
| # Add some test code to play with the component while it's in development. | ||
| # During development, we can run this just as we would any other Streamlit | ||
| # app: `$ streamlit run {{ cookiecutter.import_name }}/example.py` | ||
|
|
||
| st.subheader("Component with constant args") | ||
|
|
||
| # Create an instance of our component with a constant `name` arg, and | ||
| # print its output value. | ||
| num_clicks = {{ cookiecutter.import_name }}("World") | ||
| st.markdown("You've clicked %s times!" % int(num_clicks)) | ||
|
|
||
| st.markdown("---") | ||
| st.subheader("Component with variable args") | ||
|
|
||
| # Create a second instance of our component whose `name` arg will vary | ||
| # based on a text_input widget. | ||
| # | ||
| # We use the special "key" argument to assign a fixed identity to this | ||
| # component instance. By default, when a component's arguments change, | ||
| # it is considered a new instance and will be re-mounted on the frontend | ||
| # and lose its current state. In this case, we want to vary the component's | ||
| # "name" argument without having it get recreated. | ||
| name_input = st.text_input("Enter a name", value="Streamlit") | ||
| num_clicks = {{ cookiecutter.import_name }}(name_input, key="foo") | ||
| st.markdown("You've clicked %s times!" % int(num_clicks)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import streamlit as st | ||
| import pandas as pd | ||
| from custom_dataframe import custom_dataframe | ||
|
|
||
| # Test code to play with the component while it's in development. | ||
| # During development, we can run this just as we would any other Streamlit | ||
| # app: `$ streamlit run custom_dataframe/example.py` | ||
| raw_data = { | ||
| "First Name": ["Jason", "Molly", "Tina", "Jake", "Amy"], | ||
| "Last Name": ["Miller", "Jacobson", "Ali", "Milner", "Smith"], | ||
| "Age": [42, 52, 36, 24, 73], | ||
| } | ||
|
|
||
| df = pd.DataFrame(raw_data, columns=["First Name", "Last Name", "Age"]) | ||
| returned_df = custom_dataframe(df) | ||
|
|
||
| if not returned_df.empty: | ||
| st.table(returned_df) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be great if the code in our templates had more docstrings. For each method you can write something to make the code easier to use. We should also type hints.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If it's ok I will do this in all utils files sync PR