text
stringlengths
0
5.92k
import inspect import warnings from taipy.gui import Gui, Markdown, State, navigate def test_navigate(gui: Gui, helpers): def navigate_to(state: State): navigate(state, "test") with warnings.catch_warnings(record=True): gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("#This is a page")) gui.run(run_server=False) client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) client.get(f"/taipy-jsx/test/?client_id={sid}") ws_client.emit("message", {"client_id": sid, "type": "A", "name": "my_button", "payload": "navigate_to"}) # assert for received message (message that would be sent to the front-end client) assert ws_client.get_received() def test_navigate_to_no_route(gui: Gui, helpers): def navigate_to(state: State): navigate(state, "toto") with warnings.catch_warnings(record=True): gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("#This is a page")) gui.run(run_server=False) client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) client.get(f"/taipy-jsx/test/?client_id={sid}") ws_client.emit("message", {"client_id": sid, "type": "A", "name": "my_button", "payload": "navigate_to"}) # assert for received message (message that would be sent to the front-end client) assert not ws_client.get_received() def test_on_navigate_to_inexistant(gui: Gui, helpers): def on_navigate(state: State, page: str): return "test2" if page == "test" else page with warnings.catch_warnings(record=True) as records: gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("#This is a page")) gui.run(run_server=False) client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) client.get(f"/taipy-jsx/test?client_id={sid}") warns = helpers.get_taipy_warnings(records) assert len(warns) == 1 text = warns[0].message.args[0] if isinstance(warns[0].message, Warning) else warns[0].message assert text == 'Cannot navigate to "test2": unknown page.' def test_on_navigate_to_existant(gui: Gui, helpers): def on_navigate(state: State, page: str): return "test2" if page == "test1" else page with warnings.catch_warnings(record=True): gui._set_frame(inspect.currentframe()) gui.add_page("test1", Markdown("#This is a page test1")) gui.add_page("test2", Markdown("#This is a page test2")) gui.run(run_server=False) client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) content = client.get(f"/taipy-jsx/test1?client_id={sid}") assert content.status_code == 302
import inspect import pandas as pd # type: ignore from taipy.gui import Gui def test_expression_text_control_str(gui: Gui, test_client, helpers): gui._bind_var_val("x", "Hello World!") md_string = "<|{x}|>" expected_list = ["<Field", 'dataType="str"', 'defaultValue="Hello World!"', "value={tpec_TpExPr_x_TPMDL_0}"] helpers.test_control_md(gui, md_string, expected_list) def test_expression_text_control_int(gui: Gui, test_client, helpers): gui._bind_var_val("x", 10) md_string = "<|{x}|>" expected_list = ["<Field", 'dataType="int"', 'defaultValue="10"', "value={tpec_TpExPr_x_TPMDL_0}"] helpers.test_control_md(gui, md_string, expected_list) def test_expression_text_control_1(gui: Gui, test_client, helpers): gui._set_frame(inspect.currentframe()) gui._bind_var_val("x", 10) gui._bind_var_val("y", 20) md_string = "<|{x + y}|>" expected_list = [ "<Field", 'dataType="int"', 'defaultValue="30"', "value={tp_TpExPr_x_y_TPMDL_0_0}", ] helpers.test_control_md(gui, md_string, expected_list) def test_expression_text_control_2(gui: Gui, test_client, helpers): gui._set_frame(inspect.currentframe()) gui._bind_var_val("x", 10) gui._bind_var_val("y", 20) md_string = "<|x + y = {x + y}|>" expected_list = [ "<Field", 'dataType="str"', 'defaultValue="x + y = 30"', "value={tp_TpExPr_x_y_x_y_TPMDL_0_0}", ] helpers.test_control_md(gui, md_string, expected_list) def test_expression_text_control_3(gui: Gui, test_client, helpers): gui._set_frame(inspect.currentframe()) gui._bind_var_val("x", "Mickey Mouse") gui._bind_var_val("y", "Donald Duck") md_string = "<|Hello {x} and {y}|>" expected_list = [ "<Field", 'dataType="str"', 'defaultValue="Hello Mickey Mouse and Donald Duck"', "value={tp_TpExPr_Hello_x_and_y_TPMDL_0_0}", ] helpers.test_control_md(gui, md_string, expected_list) def test_expression_text_gt_operator(gui: Gui, test_client, helpers): gui._set_frame(inspect.currentframe()) gui._bind_var_val("x", 0) md_string = "<|{x > 0}|>" expected_list = [ "<Field", 'dataType="bool"', 'defaultValue="false"', "value={tp_TpExPr_x_0_TPMDL_0_0}", ] helpers.test_control_md(gui, md_string, expected_list) def test_expression_button_control(gui: Gui, test_client, helpers): gui._bind_var_val("label", "A button label") md_string = "<|button|label={label}|>" expected_list = ["<Button", 'defaultLabel="A button label"', "label={tpec_TpExPr_label_TPMDL_0}"] helpers.test_control_md(gui, md_string, expected_list) def test_expression_table_control(gui: Gui, test_client, helpers): gui._set_frame(inspect.currentframe()) gui._bind_var_val("pd", pd) gui._bind_var_val("series_1", pd.Series(["a", "b", "c"], name="Letters")) gui._bind_var_val("series_2", pd.Series([1, 2, 3], name="Numbers")) md_string = "<|{pd.concat([series_1, series_2], axis=1)}|table|columns=Letters;Numbers|>" expected_list = [ "<Table", 'defaultColumns="{&quot;Letters&quot;: &#x7B;&quot;index&quot;: 0, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Letters&quot;&#x7D;, &quot;Numbers&quot;: &#x7B;&quot;index&quot;: 1, &quot;type&quot;: &quot;int&quot;, &quot;dfid&quot;: &quot;Numbers&quot;&#x7D;}"', 'updateVarName="_TpD_tp_TpExPr_pd_concat_series_1_series_2_axis_1_TPMDL_0_0"', "data={_TpD_tp_TpExPr_pd_concat_series_1_series_2_axis_1_TPMDL_0_0}", ] helpers.test_control_md(gui, md_string, expected_list) assert isinstance(gui._get_data_scope().tp_TpExPr_pd_concat_series_1_series_2_axis_1_TPMDL_0_0, pd.DataFrame) def test_lambda_expression_selector(gui: Gui, test_client, helpers): gui._bind_var_val( "lov", [ {"id": "1", "name": "scenario 1"}, {"id": "3", "name": "scenario 3"}, {"id": "2", "name": "scenario 2"}, ], ) gui._bind_var_val("sel", {"id": "1", "name": "scenario 1"}) md_string = "<|{sel}|selector|lov={lov}|type=test|adapter={lambda elt: (elt['id'], elt['name'])}|>" expected_list = [ "<Selector", 'defaultLov="[[&quot;1&quot;, &quot;scenario 1&quot;], [&quot;3&quot;, &quot;scenario 3&quot;], [&quot;2&quot;, &quot;scenario 2&quot;]]"', 'defaultValue="[&quot;1&quot;]"', 'updateVars="lov=_TpL_tpec_TpExPr_lov_TPMDL_0"', "lov={_TpL_tpec_TpExPr_lov_TPMDL_0}", 'updateVarName="_TpLv_tpec_TpExPr_sel_TPMDL_0"', "value={_TpLv_tpec_TpExPr_sel_TPMDL_0}", ] helpers.test_control_md(gui, md_string, expected_list)
import numpy as np import pandas as pd from taipy.gui.data.decimator.lttb import LTTB from taipy.gui.data.decimator.minmax import MinMaxDecimator from taipy.gui.data.decimator.rdp import RDP from taipy.gui.data.decimator.scatter_decimator import ScatterDecimator from taipy.gui.data.utils import _df_data_filter def test_data_filter_1(csvdata): df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", MinMaxDecimator(100), {}, False) assert df.shape[0] == 100 def test_data_filter_2(csvdata): df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", LTTB(100), {}, False) assert df.shape[0] == 100 def test_data_filter_3(csvdata): df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", RDP(n_out=100), {}, False) assert df.shape[0] == 100 def test_data_filter_4(csvdata): df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", RDP(epsilon=100), {}, False) assert df.shape[0] == 18 def test_data_filter_5(csvdata): df, _ = _df_data_filter( csvdata[:1500], None, "Daily hospital occupancy", "", ScatterDecimator(), {"width": 200, "height": 100}, False ) assert df.shape[0] == 1150
# # 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 inspect import pytest from taipy.gui import Gui, Markdown from .state_asset.page1 import get_a, md_page1, set_a def test_state(gui: Gui): a = 10 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page("page1", md_page1) gui.run(run_server=False, single_client=True) state = gui._Gui__state with gui.get_flask_app().app_context(): assert state.a == 10 assert state["page1"].a == 20 assert state["tests.taipy.gui.gui_specific.state_asset.page1"].a == 20 assert state._gui == gui with pytest.raises(Exception) as e: state.b assert e.value.args[0] == "Variable 'b' is not defined." with pytest.raises(Exception) as e: state.b = 10 assert e.value.args[0] == "Variable 'b' is not accessible." with pytest.raises(Exception) as e: state._taipy_p1 assert e.value.args[0] == "Variable '_taipy_p1' is protected and is not accessible." with pytest.raises(Exception) as e: state._taipy_p1 = 10 assert e.value.args[0] == "Variable '_taipy_p1' is not accessible." assert state._get_placeholder("_taipy_p1") is None state._set_placeholder("_taipy_p1", 10) assert state._get_placeholder("_taipy_p1") == 10 assert state._get_placeholder_attrs() == ( "_taipy_p1", "_current_context", ) assert get_a(state) == 20 set_a(state, 30) assert get_a(state) == 30
import pytest from taipy.gui import Gui from taipy.gui.utils._locals_context import _LocalsContext def test_locals_context(gui: Gui): lc = _LocalsContext() gui.run(run_server=False) with gui.get_flask_app().app_context(): with pytest.raises(KeyError): lc.get_default() current_locals = locals() lc.set_default(current_locals) assert lc.get_default() == current_locals temp_locals = {"__main__": "test"} lc.add("test", temp_locals) assert lc.get_context() is None assert lc.get_locals() == current_locals with lc.set_locals_context("test"): assert lc.get_context() == "test" assert lc.get_locals() == temp_locals assert lc.get_context() is None assert lc.get_locals() == current_locals assert lc.is_default() is True assert "__main__" in lc.get_all_keys()
import inspect from taipy.gui.utils.get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var x = 10 def test_get_module_name(): assert "tests.taipy.gui.gui_specific.test_get_module_name" == _get_module_name_from_frame(inspect.currentframe()) def test_get_module_name_imported_var(): assert "tests.taipy.gui.gui_specific.test_get_module_name" == _get_module_name_from_imported_var( "x", 10, "test_get_module_name" ) assert "test_get_module_name" == _get_module_name_from_imported_var("x", 11, "test_get_module_name")
import inspect import os from pathlib import Path from taipy.gui import Gui def test_folder_pages_binding(gui: Gui): folder_path = f"{Path(Path(__file__).parent.resolve())}{os.path.sep}sample_assets" gui._set_frame(inspect.currentframe()) gui.add_pages(folder_path) gui.run(run_server=False) assert len(gui._config.routes) == 3 # 2 files -> 2 routes + 1 default route assert len(gui._config.pages) == 3 # 2 files -> 2 pages + 1 default page
import inspect import json import warnings from taipy.gui import Gui def test_render_route(gui: Gui): gui._set_frame(inspect.currentframe()) gui.add_page("page1", "# first page") gui.add_page("page2", "# second page") gui.run(run_server=False) with warnings.catch_warnings(record=True): client = gui._server.test_client() response = client.get("/taipy-init") response_data = json.loads(response.get_data().decode("utf-8", "ignore")) assert response.status_code == 200 assert isinstance(response_data, dict) assert isinstance(response_data["locations"], dict) assert "/page1" in response_data["locations"] assert "/page2" in response_data["locations"] assert "/" in response_data["locations"] assert response_data["locations"] == {"/": "/TaiPy_root_page", "/page1": "/page1", "/page2": "/page2"}
import json import pandas as pd import pytest from taipy.gui import Gui from taipy.gui.utils import _TaipyContent def test__get_real_var_name(gui: Gui): res = gui._get_real_var_name("") assert isinstance(res, tuple) assert res[0] == "" assert res[1] == "" gui.run(run_server=False) with gui.get_flask_app().app_context(): with pytest.raises(NameError): res = gui._get_real_var_name(f"{_TaipyContent.get_hash()}_var") def test__get_user_instance(gui: Gui): gui.run(run_server=False) with gui.get_flask_app().app_context(): with pytest.warns(UserWarning): gui._get_user_instance("", type(None)) def test__call_broadcast_callback(gui: Gui): gui.run(run_server=False) with gui.get_flask_app().app_context(): res = gui._call_broadcast_callback(lambda s, t: t, ["Hello World"], "mine") assert res == "Hello World" with gui.get_flask_app().app_context(): with pytest.warns(UserWarning): res = gui._call_broadcast_callback(print, ["Hello World"], "mine") assert res is None def test__refresh_expr(gui: Gui): gui.run(run_server=False) with gui.get_flask_app().app_context(): res = gui._refresh_expr("var", None) assert res is None def test__tbl_cols(gui: Gui): data = pd.DataFrame({"col1": [0, 1, 2], "col2": [True, True, False]}) gui.run(run_server=False) with gui.get_flask_app().app_context(): res = gui._tbl_cols(True, None, json.dumps({}), json.dumps({"data": "data"}), data=data) d = json.loads(res) assert isinstance(d, dict) assert d["col1"]["type"] == "int" res = gui._tbl_cols(False, None, "", "") assert repr(res) == "Taipy: Do not update" def test__chart_conf(gui: Gui): data = pd.DataFrame({"col1": [0, 1, 2], "col2": [True, True, False]}) gui.run(run_server=False) with gui.get_flask_app().app_context(): res = gui._chart_conf(True, None, json.dumps({}), json.dumps({"data": "data"}), data=data) d = json.loads(res) assert isinstance(d, dict) assert d["columns"]["col1"]["type"] == "int" res = gui._chart_conf(False, None, "", "") assert repr(res) == "Taipy: Do not update" with pytest.warns(UserWarning): res = gui._chart_conf(True, None, "", "") assert repr(res) == "Taipy: Do not update" def test__get_valid_adapter_result(gui: Gui): gui.run(run_server=False) with gui.get_flask_app().app_context(): res = gui._get_valid_adapter_result(("id", "label")) assert isinstance(res, tuple) assert res[0] == "id"
import json import warnings from types import SimpleNamespace from taipy.gui import Gui, Markdown def test_partial(gui: Gui): with warnings.catch_warnings(record=True): gui.add_partial(Markdown("#This is a partial")) gui.run(run_server=False) client = gui._server.test_client() response = client.get(f"/taipy-jsx/{gui._config.partial_routes[0]}") response_data = json.loads(response.get_data().decode("utf-8", "ignore")) assert response.status_code == 200 assert "jsx" in response_data and "This is a partial" in response_data["jsx"] def test_partial_update(gui: Gui): with warnings.catch_warnings(record=True): partial = gui.add_partial(Markdown("#This is a partial")) gui.run(run_server=False, single_client=True) client = gui._server.test_client() response = client.get(f"/taipy-jsx/{gui._config.partial_routes[0]}") response_data = json.loads(response.get_data().decode("utf-8", "ignore")) assert response.status_code == 200 assert "jsx" in response_data and "This is a partial" in response_data["jsx"] # update partial fake_state = SimpleNamespace() fake_state._gui = gui partial.update_content(fake_state, "#partial updated") # type: ignore response = client.get(f"/taipy-jsx/{gui._config.partial_routes[0]}") response_data = json.loads(response.get_data().decode("utf-8", "ignore")) assert response.status_code == 200 assert "jsx" in response_data and "partial updated" in response_data["jsx"]
from taipy.gui import Gui, Markdown def test_variable_binding(helpers): """ Tests the binding of a few variables and a function """ def another_function(gui): pass x = 10 y = 20 z = "button label" gui = Gui() gui.add_page("test", Markdown("<|{x}|> | <|{y}|> | <|{z}|button|on_action=another_function|>")) gui.run(run_server=False, single_client=True) client = gui._server.test_client() jsx = client.get("/taipy-jsx/test").json["jsx"] for expected in ["<Button", 'defaultLabel="button label"', "label={tpec_TpExPr_z_TPMDL_0}"]: assert expected in jsx assert gui._bindings().x == x assert gui._bindings().y == y assert gui._bindings().z == z with gui.get_flask_app().app_context(): assert callable(gui._get_user_function("another_function")) helpers.test_cleanup() def test_properties_binding(helpers): gui = Gui() modifier = "nice " # noqa: F841 button_properties = {"label": "A {modifier}button"} # noqa: F841 gui.add_page("test", Markdown("<|button|properties=button_properties|>")) gui.run(run_server=False) client = gui._server.test_client() jsx = client.get("/taipy-jsx/test").json["jsx"] for expected in ["<Button", 'defaultLabel="A nice button"']: assert expected in jsx helpers.test_cleanup() def test_dict_binding(helpers): """ Tests the binding of a dictionary property """ d = {"k": "test"} # noqa: F841 gui = Gui("<|{d.k}|>") gui.run(run_server=False) client = gui._server.test_client() jsx = client.get("/taipy-jsx/TaiPy_root_page").json["jsx"] for expected in ["<Field", 'defaultValue="test"']: assert expected in jsx helpers.test_cleanup()
from taipy.gui import Markdown a = 20 def get_a(state): return state.a def set_a(state, val): state.a = val md_page1 = Markdown( """ <|{a}|> """ )
import inspect import pytest from taipy.gui import Gui from taipy.gui.extension import Element, ElementLibrary class MyLibrary(ElementLibrary): def get_name(self) -> str: return "taipy_extension_example" def get_elements(self): return dict() def test_extension_no_config(gui: Gui, helpers): gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() with pytest.warns(UserWarning): ret = flask_client.get("/taipy-extension/toto/titi") assert ret.status_code == 404 def test_extension_config_wrong_path(gui: Gui, helpers): Gui.add_library(MyLibrary()) gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() with pytest.warns(UserWarning): ret = flask_client.get("/taipy-extension/taipy_extension_example/titi") assert ret.status_code == 404
import inspect import pytest from flask import g from taipy.gui import Gui def test_get_status(gui: Gui): gui.run(run_server=False) flask_client = gui._server.test_client() ret = flask_client.get("/taipy.status.json") assert ret.status_code == 200, f"status_code => {ret.status_code} != 200" assert ret.mimetype == "application/json", f"mimetype => {ret.mimetype} != application/json" assert ret.json, "json is not defined" assert "gui" in ret.json, "json has no key gui" gui = ret.json.get("gui") assert isinstance(gui, dict), "json.gui is not a dict" assert "user_status" in gui, "json.gui has no key user_status" assert gui.get("user_status") == "", "json.gui.user_status is not empty" def test_get_extended_status(gui: Gui): gui.run(run_server=False, extended_status=True) flask_client = gui._server.test_client() ret = flask_client.get("/taipy.status.json") assert ret.status_code == 200, f"status_code => {ret.status_code} != 200" assert ret.mimetype == "application/json", f"mimetype => {ret.mimetype} != application/json" assert ret.json, "json is not defined" gui = ret.json.get("gui") assert "backend_version" in gui, "json.gui has no key backend_version" assert "flask_version" in gui, "json.gui has no key flask_version" assert "frontend_version" in gui, "json.gui has no key frontend_version" assert "host" in gui, "json.gui has no key host" assert "python_version" in gui, "json.gui has no key python_version" assert "user_status" in gui, "json.gui has no key user_status" assert gui.get("user_status") == "", "json.gui.user_status is not empty" def test_get_status_with_user_status(gui: Gui): user_status = "user_status" def on_status(state): return user_status gui._set_frame(inspect.currentframe()) gui.run(run_server=False) flask_client = gui._server.test_client() ret = flask_client.get("/taipy.status.json") assert ret.status_code == 200, f"status_code => {ret.status_code} != 200" assert ret.json, "json is not defined" gui = ret.json.get("gui") assert "user_status" in gui, "json.gui has no key user_status" assert gui.get("user_status") == user_status, f'json.gui.user_status => {gui.get("user_status")} != {user_status}'
import inspect import io import pathlib import tempfile import pytest from taipy.gui import Gui from taipy.gui.data.data_scope import _DataScopes from taipy.gui.utils import _get_non_existent_file_path def test_file_upload_no_varname(gui: Gui, helpers): gui.run(run_server=False) flask_client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) with pytest.warns(UserWarning): ret = flask_client.post(f"/taipy-uploads?client_id={sid}") assert ret.status_code == 400 def test_file_upload_no_blob(gui: Gui, helpers): gui.run(run_server=False) flask_client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) with pytest.warns(UserWarning): ret = flask_client.post(f"/taipy-uploads?client_id={sid}", data={"var_name": "varname"}) assert ret.status_code == 400 def test_file_upload_no_filename(gui: Gui, helpers): gui.run(run_server=False) flask_client = gui._server.test_client() file = (io.BytesIO(b"abcdef"), "") # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) with pytest.warns(UserWarning): ret = flask_client.post(f"/taipy-uploads?client_id={sid}", data={"var_name": "varname", "blob": file}) assert ret.status_code == 400 def test_file_upload_simple(gui: Gui, helpers): gui.run(run_server=False) flask_client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) file_name = "test.jpg" file = (io.BytesIO(b"abcdef"), file_name) upload_path = pathlib.Path(gui._get_config("upload_folder", tempfile.gettempdir())) file_name = _get_non_existent_file_path(upload_path, file_name).name ret = flask_client.post( f"/taipy-uploads?client_id={sid}", data={"var_name": "varname", "blob": file}, content_type="multipart/form-data", ) assert ret.status_code == 200 created_file = upload_path / file_name assert created_file.exists() def test_file_upload_multi_part(gui: Gui, helpers): gui.run(run_server=False) flask_client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) file_name = "test2.jpg" file0 = (io.BytesIO(b"abcdef"), file_name) file1 = (io.BytesIO(b"abcdef"), file_name) upload_path = pathlib.Path(gui._get_config("upload_folder", tempfile.gettempdir())) file_name = _get_non_existent_file_path(upload_path, file_name).name ret = flask_client.post( f"/taipy-uploads?client_id={sid}", data={"var_name": "varname", "blob": file0, "total": "2", "part": "0"}, content_type="multipart/form-data", ) assert ret.status_code == 200 file0_path = upload_path / f"{file_name}.part.0" assert file0_path.exists() ret = flask_client.post( f"/taipy-uploads?client_id={sid}", data={"var_name": "varname", "blob": file1, "total": "2", "part": "1"}, content_type="multipart/form-data", ) assert ret.status_code == 200 file1_path = upload_path / f"{file_name}.part.1" assert file1_path.exists() file_path = upload_path / file_name assert file_path.exists() def test_file_upload_multiple(gui: Gui, helpers): var_name = "varname" gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() with gui.get_flask_app().app_context(): gui._bind_var_val(var_name, None) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = _DataScopes._GLOBAL_ID file = (io.BytesIO(b"abcdef"), "test.jpg") ret = flask_client.post( f"/taipy-uploads?client_id={sid}", data={"var_name": var_name, "blob": file}, content_type="multipart/form-data" ) assert ret.status_code == 200 created_file = pathlib.Path(gui._get_config("upload_folder", tempfile.gettempdir())) / "test.jpg" assert created_file.exists() file2 = (io.BytesIO(b"abcdef"), "test2.jpg") ret = flask_client.post( f"/taipy-uploads?client_id={sid}", data={"var_name": var_name, "blob": file2, "multiple": "True"}, content_type="multipart/form-data", ) assert ret.status_code == 200 created_file = pathlib.Path(gui._get_config("upload_folder", tempfile.gettempdir())) / "test2.jpg" assert created_file.exists() value = getattr(gui._bindings()._get_all_scopes()[sid], var_name) assert len(value) == 2
import pathlib import pytest from taipy.gui import Gui def test_image_path_not_found(gui: Gui, helpers): gui.run(run_server=False) flask_client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) ret = flask_client.get(f"/taipy-images/images/img.png?client_id={sid}") assert ret.status_code == 404 def test_image_path_found(gui: Gui, helpers): url = gui._get_content( "img", str((pathlib.Path(__file__).parent.parent.parent / "resources" / "fred.png").resolve()), True ) gui.run(run_server=False) flask_client = gui._server.test_client() # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) ret = flask_client.get(f"{url}?client_id={sid}") assert ret.status_code == 200 def test_image_data_too_big(gui: Gui, helpers): with open((pathlib.Path(__file__).parent.parent.parent / "resources" / "taipan.jpg"), "rb") as big_file: url = gui._get_content("img", big_file.read(), True) assert not url.startswith("data:")
import inspect import pytest from taipy.gui import Gui def test_user_content_without_callback(gui: Gui, helpers): gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() with pytest.warns(UserWarning): ret = flask_client.get(gui._get_user_content_url("path")) assert ret.status_code == 404 def test_user_content_with_wrong_callback(gui: Gui, helpers): def on_user_content_cb(state, path, args): return None on_user_content = on_user_content_cb gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() with pytest.warns(UserWarning): ret = flask_client.get(gui._get_user_content_url("path", {"a": "b"})) assert ret.status_code == 404 def test_user_content_with_callback(gui: Gui, helpers): def on_user_content_cb(state, path, args): return "" on_user_content = on_user_content_cb gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() ret = flask_client.get(gui._get_user_content_url("path")) assert ret.status_code == 200
import inspect from taipy.gui import Gui, Markdown from taipy.gui.data.data_scope import _DataScopes def test_sending_messages_in_group(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) cid = _DataScopes._GLOBAL_ID # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") assert gui._bindings()._get_all_scopes()[cid].name == "World!" # type: ignore assert gui._bindings()._get_all_scopes()[cid].btn_id == "button1" # type: ignore with gui.get_flask_app().test_request_context(f"/taipy-jsx/test/?client_id={cid}", data={"client_id": cid}): with gui as aGui: aGui._Gui__state.name = "Monde!" aGui._Gui__state.btn_id = "button2" assert gui._bindings()._get_all_scopes()[cid].name == "Monde!" assert gui._bindings()._get_all_scopes()[cid].btn_id == "button2" # type: ignore received_messages = ws_client.get_received() helpers.assert_outward_ws_multiple_message(received_messages[0], "MS", 2)
import inspect import logging import pathlib import pytest from taipy.gui import Gui, download def test_download_file(gui: Gui, helpers): def do_something(state, id): download(state, (pathlib.Path(__file__).parent.parent.parent / "resources" / "taipan.jpg")) # Bind a page so that the function will be called # gui.add_page( # "test", Markdown("<|Do something!|button|on_action=do_something|id=my_button|>") # ) # set gui frame gui._set_frame(inspect.currentframe()) gui.run(run_server=False) # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) ws_client.emit("message", {"client_id": sid, "type": "A", "name": "my_button", "payload": "do_something"}) # assert for received message (message that would be sent to the front-end client) received_messages = ws_client.get_received() assert len(received_messages) == 1 assert isinstance(received_messages[0], dict) assert "name" in received_messages[0] and received_messages[0]["name"] == "message" assert "args" in received_messages[0] args = received_messages[0]["args"] assert "type" in args and args["type"] == "DF" assert "content" in args and args["content"] == "/taipy-content/taipyStatic0/taipan.jpg" logging.getLogger().debug(args["content"])
import inspect from taipy.gui import Gui, Markdown def ws_u_assert_template(gui: Gui, helpers, value_before_update, value_after_update, payload): # Bind test variable var = value_before_update # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) # Bind a page so that the variable will be evaluated as expression gui.add_page("test", Markdown("<|{var}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) flask_client.get(f"/taipy-jsx/test?client_id={sid}") assert gui._bindings()._get_all_scopes()[sid].var == value_before_update ws_client.emit("message", {"client_id": sid, "type": "U", "name": "tpec_TpExPr_var_TPMDL_0", "payload": payload}) assert gui._bindings()._get_all_scopes()[sid].var == value_after_update # assert for received message (message that would be sent to the front-end client) received_message = ws_client.get_received() assert len(received_message) helpers.assert_outward_ws_message(received_message[0], "MU", "tpec_TpExPr_var_TPMDL_0", value_after_update) def test_ws_u_string(gui: Gui, helpers): value_before_update = "a random string" value_after_update = "a random string is added" payload = {"value": value_after_update} # set gui frame gui._set_frame(inspect.currentframe()) ws_u_assert_template(gui, helpers, value_before_update, value_after_update, payload) def test_ws_u_number(gui: Gui, helpers): value_before_update = 10 value_after_update = "11" payload = {"value": value_after_update} # set gui frame gui._set_frame(inspect.currentframe()) ws_u_assert_template(gui, helpers, value_before_update, value_after_update, payload)
import inspect from taipy.gui import Gui, Markdown def test_du_table_data_fetched(gui: Gui, helpers, csvdata): # Bind test variables csvdata = csvdata # set gui frame gui._set_frame(inspect.currentframe()) Gui._set_timezone("UTC") # Bind a page so that the variable will be evaluated as expression gui.add_page( "test", Markdown( "<|{csvdata}|table|page_size=10|page_size_options=10;30;100|columns=Day;Entity;Code;Daily hospital occupancy|date_format=eee dd MMM yyyy|>" ), ) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) sid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={sid}") ws_client.emit( "message", { "client_id": sid, "type": "DU", "name": "_TpD_tpec_TpExPr_csvdata_TPMDL_0", "payload": { "columns": ["Day", "Entity", "Code", "Daily hospital occupancy"], "pagekey": "0-100--asc", "start": 0, "end": 9, "orderby": "", "sort": "asc", }, }, ) # assert for received message (message that would be sent to the front-end client) received_messages = ws_client.get_received() assert received_messages helpers.assert_outward_ws_message( received_messages[0], "MU", "_TpD_tpec_TpExPr_csvdata_TPMDL_0", { "data": [ { "Code": "AUT", "Day_str": "2020-04-01T00:00:00.000000Z", "Daily hospital occupancy": 856, "Entity": "Austria", "_tp_index": 0, }, { "Code": "AUT", "Day_str": "2020-04-02T00:00:00.000000Z", "Daily hospital occupancy": 823, "Entity": "Austria", "_tp_index": 1, }, { "Code": "AUT", "Day_str": "2020-04-03T00:00:00.000000Z", "Daily hospital occupancy": 829, "Entity": "Austria", "_tp_index": 2, }, { "Code": "AUT", "Day_str": "2020-04-04T00:00:00.000000Z", "Daily hospital occupancy": 826, "Entity": "Austria", "_tp_index": 3, }, { "Code": "AUT", "Day_str": "2020-04-05T00:00:00.000000Z", "Daily hospital occupancy": 712, "Entity": "Austria", "_tp_index": 4, }, { "Code": "AUT", "Day_str": "2020-04-06T00:00:00.000000Z", "Daily hospital occupancy": 824, "Entity": "Austria", "_tp_index": 5, }, { "Code": "AUT", "Day_str": "2020-04-07T00:00:00.000000Z", "Daily hospital occupancy": 857, "Entity": "Austria", "_tp_index": 6, }, { "Code": "AUT", "Day_str": "2020-04-08T00:00:00.000000Z", "Daily hospital occupancy": 829, "Entity": "Austria", "_tp_index": 7, }, { "Code": "AUT", "Day_str": "2020-04-09T00:00:00.000000Z", "Daily hospital occupancy": 820, "Entity": "Austria", "_tp_index": 8, }, { "Code": "AUT", "Day_str": "2020-04-10T00:00:00.000000Z", "Daily hospital occupancy": 771, "Entity": "Austria", "_tp_index": 9, }, ], "rowcount": 14477, "start": 0, "format": "JSON", }, )
import inspect import pytest from taipy.gui import Gui, Markdown def test_default_on_change(gui: Gui, helpers): st = {"d": False} def on_change(state, var, value): st["d"] = True x = 10 # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|{x}|input|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) flask_client.get(f"/taipy-jsx/test?client_id={sid}") # fake var update ws_client.emit("message", {"client_id": sid, "type": "U", "name": "x", "payload": {"value": "20"}}) assert ws_client.get_received() assert st["d"] is True def test_specific_on_change(gui: Gui, helpers): st = {"d": False, "s": False} def on_change(state, var, value): st["d"] = True def on_input_change(state, var, value): st["s"] = True x = 10 # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|{x}|input|on_change=on_input_change|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) flask_client.get(f"/taipy-jsx/test?client_id={sid}") # fake var update ws_client.emit( "message", {"client_id": sid, "type": "U", "name": "x", "payload": {"value": "20", "on_change": "on_input_change"}}, ) assert ws_client.get_received() assert st["s"] is True assert st["d"] is False
import inspect import pytest from taipy.gui import Gui, Markdown def test_ru_selector(gui: Gui, helpers, csvdata): # Bind test variables selected_val = ["value1", "value2"] # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) # Bind a page so that the variable will be evaluated as expression gui.add_page( "test", Markdown("<|{selected_val}|selector|multiple|>"), ) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) sid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={sid}") ws_client.emit("message", {"client_id": sid, "type": "RU", "name": "", "payload": {"names": ["selected_val"]}}) # assert for received message (message that would be sent to the front-end client) received_messages = ws_client.get_received() assert len(received_messages) helpers.assert_outward_ws_message(received_messages[0], "MU", "selected_val", ["value1", "value2"])
# # 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 inspect import pytest from taipy.gui import Gui, Markdown def test_broadcast(gui: Gui, helpers): # Bind test variables selected_val = ["value1", "value2"] # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) # Bind a page so that the variable will be evaluated as expression gui.add_page( "test", Markdown("<|{selected_val}|selector|multiple|>"), ) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) sid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={sid}") gui._broadcast("broadcast_name", "broadcast_value") received_messages = ws_client.get_received() assert len(received_messages) helpers.assert_outward_simple_ws_message(received_messages[0], "U", "_bc_broadcast_name", "broadcast_value")
import inspect import time from taipy.gui import Gui, Markdown def test_a_button_pressed(gui: Gui, helpers): def do_something(state, id): state.x = state.x + 10 state.text = "a random text" x = 10 # noqa: F841 text = "hi" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) # Bind a page so that the variable will be evaluated as expression gui.add_page( "test", Markdown("<|Do something!|button|on_action=do_something|id=my_button|> | <|{x}|> | <|{text}|>") ) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) # Get the jsx once so that the page will be evaluated -> variable will be registered sid = helpers.create_scope_and_get_sid(gui) flask_client.get(f"/taipy-jsx/test?client_id={sid}") assert gui._bindings()._get_all_scopes()[sid].x == 10 # type: ignore assert gui._bindings()._get_all_scopes()[sid].text == "hi" # type: ignore ws_client.emit("message", {"client_id": sid, "type": "A", "name": "my_button", "payload": "do_something"}) assert gui._bindings()._get_all_scopes()[sid].text == "a random text" assert gui._bindings()._get_all_scopes()[sid].x == 20 # type: ignore # assert for received message (message that would be sent to the front-end client) received_messages = ws_client.get_received() helpers.assert_outward_ws_message(received_messages[0], "MU", "x", 20) helpers.assert_outward_ws_message(received_messages[1], "MU", "text", "a random text")
import inspect import warnings from flask import g from taipy.gui import Gui from taipy.gui.utils.types import _TaipyNumber def test_unbind_variable_in_expression(gui: Gui, helpers): gui.run(run_server=False, single_client=True) with warnings.catch_warnings(record=True) as records: with gui.get_flask_app().app_context(): gui._evaluate_expr("{x}") warns = helpers.get_taipy_warnings(records) assert len(warns) == 3 assert "Variable 'x' is not available in" in str(warns[0].message) assert "Variable 'x' is not defined" in str(warns[1].message) assert "Cannot evaluate expression 'x'" in str(warns[2].message) assert "name 'x' is not defined" in str(warns[2].message) def test_evaluate_same_expression_multiple_times(gui: Gui): x = 10 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) with gui.get_flask_app().app_context(): s1 = gui._evaluate_expr("x + 10 = {x + 10}") s2 = gui._evaluate_expr("x + 10 = {x + 10}") assert s1 == s2 def test_evaluate_expressions_same_variable(gui: Gui): x = 10 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) with gui.get_flask_app().app_context(): s1 = gui._evaluate_expr("x + 10 = {x + 10}") s2 = gui._evaluate_expr("x = {x}") assert "tp_TpExPr_x" in s1 and "tp_TpExPr_x" in s2 def test_evaluate_holder(gui: Gui): x = 10 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) with warnings.catch_warnings(record=True): with gui.get_flask_app().app_context(): gui._evaluate_expr("{x + 10}") hash = gui._evaluate_bind_holder(_TaipyNumber, "TpExPr_x + 10_TPMDL_0") assert "_TpN_tp_TpExPr_x_10_TPMDL_0_0" in hash lst = gui._evaluate_holders("TpExPr_x + 10_TPMDL_0") assert len(lst) == 1 assert "_TpN_tp_TpExPr_x_10_TPMDL_0_0" in lst[0] # test re-evaluate holders gui._bindings().x = 20 gui._re_evaluate_expr(lst[0]) def test_evaluate_not_expression_type(gui: Gui): gui.run(run_server=False) with gui.get_flask_app().app_context(): assert "x + 10" == gui._evaluate_expr("x + 10") def test_evaluate_expression_2_clients(gui: Gui): x = 10 # noqa: F841 y = 20 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.run(run_server=False) with gui.get_flask_app().app_context(): gui._bindings()._get_or_create_scope("A") gui._bindings()._get_or_create_scope("B") g.client_id = "A" gui._evaluate_expr("x + y = {x + y}") g.client_id = "B" gui._evaluate_expr("x") gui._re_evaluate_expr("x")
import inspect import pytest from taipy.gui.gui import Gui from taipy.gui.utils import _MapDict def test_map_dict(): d = {"a": 1, "b": 2, "c": 3} md = _MapDict(d) md_copy = _MapDict(d).copy() assert len(md) == 3 assert md.__getitem__("a") == d["a"] md.__setitem__("a", 4) assert md.__getitem__("a") == 4 assert d["a"] == 4 v1 = d["b"] v2 = md.pop("b") assert v1 == v2 assert "b" not in d.keys() assert "c" in md assert len(md) == 2 v1 = d["c"] v2 = md.popitem() assert v2 == ("c", v1) assert len(md) == 1 md.clear() assert len(md) == 0 assert len(d) == 0 assert len(md_copy) == 3 v1 = "" for k in md_copy: v1 += k assert v1 == "abc" v1 = "" for k in md_copy.keys(): v1 += k assert v1 == "abc" v1 = "" for k in md_copy.__reversed__(): v1 += k assert v1 == "cba" v1 = 0 for k in md_copy.values(): v1 += k assert v1 == 6 # 1+2+3 v1 = md_copy.setdefault("a", 5) assert v1 == 1 v1 = md_copy.setdefault("d", 5) assert v1 == 5 try: md = _MapDict("not_a_dict") assert False except Exception: assert True pass def test_map_dict_update(): update_values = {} def update(k, v): update_values[0] = k update_values[1] = v pass d = {"a": 1, "b": "2"} md = _MapDict(d, update) md.__setitem__("a", 3) assert update_values[0] == "a" assert update_values[1] == 3 pass def test_map_dict_update_full_dictionary_1(): values = {"a": 1, "b": 2} update_values = {"a": 3, "b": 5} md = _MapDict(values) assert md["a"] == 1 assert md["b"] == 2 md.update(update_values) assert md["a"] == 3 assert md["b"] == 5 def test_map_dict_update_full_dictionary_2(): temp_values = {} def update(k, v): temp_values[k] = v values = {"a": 1, "b": 2} update_values = {"a": 3, "b": 5} md = _MapDict(values, update) assert md["a"] == 1 assert md["b"] == 2 md.update(update_values) assert temp_values["a"] == 3 assert temp_values["b"] == 5 def test_map_dict_set(gui: Gui, test_client): d = {"a": 1} # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) with gui.get_flask_app().app_context(): assert isinstance(gui._Gui__state.d, _MapDict) gui._Gui__state.d = {"b": 2} assert isinstance(gui._Gui__state.d, _MapDict) assert len(gui._Gui__state.d) == 1 assert gui._Gui__state.d.get("a", None) is None assert gui._Gui__state.d.get("b", None) == 2 def test_map_dict_items(): def update(k, v): pass values = {"a": 1, "b": {"c": "list c"}} md = _MapDict(values) mdu = _MapDict(values, update) assert md["a"] == 1 assert isinstance(md["b"], _MapDict) assert isinstance(mdu["b"], _MapDict) assert md["b"]["c"] == "list c" assert mdu["b"]["c"] == "list c" del md["a"] with pytest.raises(KeyError): md["e"] setattr(md, "a", 1) assert md["a"] == 1
import pathlib import tempfile from taipy.gui import Gui from taipy.gui.utils import _get_non_existent_file_path def test_empty_file_name(gui: Gui, helpers): assert _get_non_existent_file_path(pathlib.Path(tempfile.gettempdir()), "").name def test_non_existent_file(gui: Gui, helpers): assert not _get_non_existent_file_path(pathlib.Path(tempfile.gettempdir()), "").exists() def test_existent_file(gui: Gui, helpers): file_path = _get_non_existent_file_path(pathlib.Path(tempfile.gettempdir()), "") with open(file_path, "w") as file_handler: file_handler.write("hello") assert file_path.exists() file_stem = file_path.stem.split(".", 1)[0] file_suffix = file_path.suffixes[-1] index = int(file_path.suffixes[0][1:]) if len(file_path.suffixes) > 1 else -1 file_path = _get_non_existent_file_path(pathlib.Path(tempfile.gettempdir()), "") assert file_path.name == f"{file_stem}.{index + 1}{file_suffix}" with open(file_path, "w") as file_handler: file_handler.write("hello 2") assert file_path.exists() file_path = _get_non_existent_file_path(pathlib.Path(tempfile.gettempdir()), "") assert file_path.name == f"{file_stem}.{index + 2}{file_suffix}"
import warnings import pytest from taipy.gui.utils.date import _string_to_date from taipy.gui.utils.types import _TaipyBase, _TaipyBool, _TaipyDate, _TaipyNumber def test_taipy_base(): tb = _TaipyBase("value", "hash") assert tb.get() == "value" assert tb.get_name() == "hash" tb.set("a value") assert tb.get() == "a value" assert tb.get_hash() == NotImplementedError def test_taipy_bool(): assert _TaipyBool(0, "v").get() is False assert _TaipyBool(1, "v").get() is True assert _TaipyBool(False, "v").get() is False assert _TaipyBool(True, "v").get() is True assert _TaipyBool("", "v").get() is False assert _TaipyBool("hey", "v").get() is True assert _TaipyBool([], "v").get() is False assert _TaipyBool(["an item"], "v").get() is True def test_taipy_number(): with pytest.raises(TypeError): _TaipyNumber("a string", "x").get() with warnings.catch_warnings(record=True): _TaipyNumber("a string", "x").cast_value("a string") _TaipyNumber(0, "x").cast_value(0) def test_taipy_date(): assert _TaipyDate(_string_to_date("2022-03-03 00:00:00 UTC"), "x").get() == "2022-03-03T00:00:00+00:00" assert _TaipyDate("2022-03-03 00:00:00 UTC", "x").get() == "2022-03-03 00:00:00 UTC" assert _TaipyDate(None, "x").get() is None _TaipyDate("", "x").cast_value("2022-03-03 00:00:00 UTC") _TaipyDate("", "x").cast_value(_string_to_date("2022-03-03 00:00:00 UTC"))
import inspect from time import sleep import pytest from taipy.gui import Gui, State, invoke_long_callback def test_long_callback(gui: Gui): status = None # noqa: F841 def heavy_function(delay=1): sleep(delay) def heavy_function_with_exception(delay=1): sleep(delay) raise Exception("Heavy function Exception") def heavy_function_status(state: State, status: int): state.status = status def on_exception(state: State, function_name: str, e: Exception): state.status = -1 gui._set_frame(inspect.currentframe()) gui.run(run_server=False, single_client=True) state = gui._Gui__state with gui.get_flask_app().app_context(): assert state.status is None invoke_long_callback(state, heavy_function) invoke_long_callback(state, heavy_function_with_exception) invoke_long_callback(state, heavy_function, (), heavy_function_status) invoke_long_callback(state, heavy_function, (2), heavy_function_status, (), 1000) invoke_long_callback(state, heavy_function_with_exception, (), heavy_function_status)
import inspect from flask import g from taipy.gui import Gui, Markdown, get_state_id def test_get_state_id(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().app_context(): g.client_id = cid assert cid == get_state_id(gui._Gui__state)
import inspect from flask import g from taipy.gui import Gui, Markdown, State, download def test_download(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 def on_download_action(state: State): pass # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().test_request_context(f"/taipy-jsx/test/?client_id={cid}", data={"client_id": cid}): g.client_id = cid download(gui._Gui__state, "some text", "filename.txt", "on_download_action") received_messages = ws_client.get_received() helpers.assert_outward_ws_simple_message( received_messages[0], "DF", {"name": "filename.txt", "onAction": "on_download_action"} )
import inspect from flask import g from taipy.gui import Gui, Markdown, navigate def test_navigate(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().test_request_context(f"/taipy-jsx/test/?client_id={cid}", data={"client_id": cid}): g.client_id = cid navigate(gui._Gui__state, "test") received_messages = ws_client.get_received() helpers.assert_outward_ws_simple_message(received_messages[0], "NA", {"to": "test"})
import inspect from flask import g from taipy.gui import Gui, Markdown, State, invoke_callback def test_invoke_callback(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 val = 1 # noqa: F841 def user_callback(state: State): state.val = 10 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>\n<|{val}|>")) gui.run(run_server=False, single_client=True) flask_client = gui._server.test_client() # client id cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().app_context(): g.client_id = cid invoke_callback(gui, cid, user_callback, []) assert gui._Gui__state.val == 10
import inspect from flask import g from taipy.gui import Gui, Markdown, hold_control def test_hold_control(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().test_request_context(f"/taipy-jsx/test/?client_id={cid}", data={"client_id": cid}): g.client_id = cid hold_control(gui._Gui__state) received_messages = ws_client.get_received() helpers.assert_outward_ws_simple_message( received_messages[0], "BL", {"action": "_taipy_on_cancel_block_ui", "message": "Work in Progress..."} )
import inspect from flask import g from taipy.gui import Gui, Markdown, resume_control def test_resume_control(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().test_request_context(f"/taipy-jsx/test/?client_id={cid}", data={"client_id": cid}): g.client_id = cid resume_control(gui._Gui__state) received_messages = ws_client.get_received() helpers.assert_outward_ws_simple_message(received_messages[0], "BL", {"message": None})
import inspect from flask import g from taipy.gui import Gui, Markdown, notify def test_notify(gui: Gui, helpers): name = "World!" # noqa: F841 btn_id = "button1" # noqa: F841 # set gui frame gui._set_frame(inspect.currentframe()) gui.add_page("test", Markdown("<|Hello {name}|button|id={btn_id}|>")) gui.run(run_server=False) flask_client = gui._server.test_client() # WS client and emit ws_client = gui._server._ws.test_client(gui._server.get_flask()) cid = helpers.create_scope_and_get_sid(gui) # Get the jsx once so that the page will be evaluated -> variable will be registered flask_client.get(f"/taipy-jsx/test?client_id={cid}") with gui.get_flask_app().test_request_context(f"/taipy-jsx/test/?client_id={cid}", data={"client_id": cid}): g.client_id = cid notify(gui._Gui__state, "Info", "Message") received_messages = ws_client.get_received() helpers.assert_outward_ws_simple_message(received_messages[0], "AL", {"atype": "Info", "message": "Message"})
import contextlib import time from urllib.request import urlopen import pytest from testbook import testbook @pytest.mark.filterwarnings("ignore::RuntimeWarning") @testbook("tests/taipy/gui/notebook/simple_gui.ipynb") def test_notebook_simple_gui(tb, helpers): tb.execute_cell("import") tb.execute_cell("page_declaration") tb.execute_cell("gui_init") tb.execute_cell("gui_run") while not helpers.port_check(): time.sleep(0.1) assert ">Hello</h1>" in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8") assert 'defaultValue=\\"10\\"' in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8") # Test state manipulation within notebook tb.execute_cell("get_variable") assert "10" in tb.cell_output_text("get_variable") assert 'defaultValue=\\"10\\"' in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8") tb.execute_cell("set_variable") assert 'defaultValue=\\"20\\"' in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8") tb.execute_cell("re_get_variable") assert "20" in tb.cell_output_text("re_get_variable") # Test page reload tb.execute_cell("gui_stop") with pytest.raises(Exception) as exc_info: urlopen("http://127.0.0.1:5000/taipy-jsx/page1") assert "501: Gateway error" in str(exc_info.value) tb.execute_cell("gui_re_run") while True: with contextlib.suppress(Exception): urlopen("http://127.0.0.1:5000/taipy-jsx/page1") break assert ">Hello</h1>" in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8") tb.execute_cell("gui_reload") while True: with contextlib.suppress(Exception): urlopen("http://127.0.0.1:5000/taipy-jsx/page1") break assert ">Hello</h1>" in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8") tb.execute_cell("gui_re_stop") with pytest.raises(Exception) as exc_info: urlopen("http://127.0.0.1:5000/taipy-jsx/page1") assert "501: Gateway error" in str(exc_info.value)
from taipy.gui import Gui, Markdown
import inspect from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_redirect(page: "Page", gui: Gui, helpers): page_md = """ <|Redirect Successfully|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() == "Redirect Successfully"
import pytest @pytest.fixture(scope="session") def browser_context_args(browser_context_args, e2e_port, e2e_base_url): return { **browser_context_args, "base_url": f"http://127.0.0.1:{e2e_port}{e2e_base_url}", "timezone_id": "Europe/Paris", } @pytest.fixture(scope="function") def gui(helpers, e2e_base_url): from taipy.gui import Gui gui = Gui() gui.load_config({"base_url": e2e_base_url, "host": "0.0.0.0" if e2e_base_url != "/" else "127.0.0.1"}) yield gui # Delete Gui instance and state of some classes after each test gui.stop() helpers.test_cleanup()
import inspect import re from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from playwright.sync_api import expect from taipy.gui import Gui @pytest.mark.teste2e def test_navbar_navigate(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) gui.add_page(name="Data", page="<|navbar|id=nav1|> <|Data|id=text-data|>") gui.add_page(name="Test", page="<|navbar|id=nav1|> <|Test|id=text-test|>") helpers.run_e2e(gui) page.goto("./Data") page.expect_websocket() page.wait_for_selector("#text-data") page.click("#nav1 button:nth-child(2)") page.wait_for_selector("#text-test") expect(page).to_have_url(re.compile(".*Test")) page.click("#nav1 button:nth-child(1)") page.wait_for_selector("#text-data") expect(page).to_have_url(re.compile(".*Data"))
import inspect from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui from taipy.gui.utils.date import _string_to_date @pytest.mark.teste2e def test_timzone_specified_1(page: "Page", gui: Gui, helpers): _timezone_test_template(page, gui, helpers, "Etc/GMT", ["2022-03-03 00:00:00 UTC"]) @pytest.mark.teste2e def test_timzone_specified_2(page: "Page", gui: Gui, helpers): _timezone_test_template( page, gui, helpers, "Europe/Paris", ["2022-03-03 01:00:00 GMT+1", "2022-03-03 01:00:00 UTC+1"] ) @pytest.mark.teste2e def test_timzone_specified_3(page: "Page", gui: Gui, helpers): _timezone_test_template( page, gui, helpers, "Asia/Ho_Chi_Minh", ["2022-03-03 07:00:00 GMT+7", "2022-03-03 07:00:00 UTC+7"] ) @pytest.mark.teste2e def test_timzone_specified_4(page: "Page", gui: Gui, helpers): _timezone_test_template( page, gui, helpers, "America/Sao_Paulo", ["2022-03-02 21:00:00 GMT-3", "2022-03-02 21:00:00 UTC−3"] ) @pytest.mark.teste2e def test_timezone_client_side(page: "Page", gui: Gui, helpers): _timezone_test_template(page, gui, helpers, "client", ["2022-03-03 01:00:00 GMT+1", "2022-03-03 01:00:00 UTC+1"]) def _timezone_test_template(page: "Page", gui: Gui, helpers, time_zone, texts): page_md = """ <|{t}|id=text1|> """ t = _string_to_date("2022-03-03T00:00:00.000Z") # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, time_zone=time_zone) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() in texts def test_date_only(page: "Page", gui: Gui, helpers): page_md = """ <|{t}|id=text1|> """ t = _string_to_date("Wed Jul 28 1993") # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() in ["1993-07-28"]
import inspect from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_accessor_json(page: "Page", gui: Gui, csvdata, helpers): table_data = csvdata # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page( name="test", page="<|{table_data}|table|columns=Day;Entity;Code;Daily hospital occupancy|date_format=eee dd MMM yyyy|id=table1|>", ) helpers.run_e2e(gui, use_arrow=False) page.goto("./test") page.expect_websocket() page.wait_for_selector("#table1 tr:nth-child(32)") # wait for data to be loaded (30 rows of skeleton while loading) assert_table_content(page) @pytest.mark.teste2e def test_accessor_arrow(page: "Page", gui: Gui, csvdata, helpers): if util.find_spec("pyarrow"): table_data = csvdata # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page( name="test", page="<|{table_data}|table|columns=Day;Entity;Code;Daily hospital occupancy|date_format=eee dd MMM yyyy|id=table1|>", ) helpers.run_e2e(gui, use_arrow=True) page.goto("./test") page.expect_websocket() page.wait_for_selector( "#table1 tr:nth-child(32)" ) # wait for data to be loaded (30 rows of skeleton while loading) assert_table_content(page) def assert_table_content(page: "Page"): # assert page.query_selector("#table1 tbody tr:nth-child(1) td:nth-child(1)").inner_text() == "Wed 01 Apr 2020" assert page.query_selector("#table1 tbody tr:nth-child(1) td:nth-child(2)").inner_text() == "Austria" assert page.query_selector("#table1 tbody tr:nth-child(1) td:nth-child(4)").inner_text() == "856"
import inspect from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_theme_light(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=False) page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") background_color = page.evaluate( 'window.getComputedStyle(document.querySelector("main"), null).getPropertyValue("background-color")' ) assert background_color == "rgb(255, 255, 255)" @pytest.mark.teste2e def test_theme_dark(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=True) page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") background_color = page.evaluate( 'window.getComputedStyle(document.querySelector("main"), null).getPropertyValue("background-color")' ) assert background_color == "rgb(18, 18, 18)"
import inspect from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_margin_1(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=False, margin="10rem") page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") margin = page.evaluate('window.getComputedStyle(document.querySelector("#root"), null).getPropertyValue("margin")') assert margin == "160px" @pytest.mark.teste2e def test_margin_2(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=False) page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") margin = page.evaluate('window.getComputedStyle(document.querySelector("#root"), null).getPropertyValue("margin")') assert margin == "16px" @pytest.mark.teste2e def test_margin_3(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=False, margin="10rem", stylekit=True) page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") margin = page.evaluate('window.getComputedStyle(document.querySelector("#root"), null).getPropertyValue("margin")') assert margin == "160px" @pytest.mark.teste2e def test_margin_4(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=False, stylekit={"root_margin": "20rem"}) page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") margin = page.evaluate('window.getComputedStyle(document.querySelector("#root"), null).getPropertyValue("margin")') assert margin == "320px" @pytest.mark.teste2e def test_margin_5(page: "Page", gui: Gui, helpers): page_md = """ <|Just a page|id=text1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui, dark_mode=False, stylekit={"root_margin": "20rem"}, margin="10rem") page.goto("./") page.expect_websocket() page.wait_for_selector("#text1") margin = page.evaluate('window.getComputedStyle(document.querySelector("#root"), null).getPropertyValue("margin")') assert margin == "320px"
import inspect import os import time from importlib import util from pathlib import Path from urllib.request import urlopen import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui, Html from taipy.gui.server import _Server @pytest.mark.teste2e def test_html_render_with_style(page: "Page", gui: Gui, helpers): html_content = """<!DOCTYPE html> <html lang="en"> <head> <style> .taipy-text { color: green; } .custom-text { color: blue; } </style> </head> <body> <taipy:text id="text1">Hey</taipy:text> <taipy:text id="text2" class="custom-text">There</taipy:text> </body> </html>""" gui._set_frame(inspect.currentframe()) gui.add_page("page1", Html(html_content)) helpers.run_e2e(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#text1") retry = 0 while ( retry < 10 and page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') != "rgb(0, 128, 0)" ): retry += 1 time.sleep(0.2) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') == "rgb(0, 128, 0)" ) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text2"), null).getPropertyValue("color")') == "rgb(0, 0, 255)" ) @pytest.mark.teste2e def test_html_render_bind_assets(page: "Page", gui: Gui, helpers, e2e_base_url, e2e_port): gui._set_frame(inspect.currentframe()) gui.add_pages(pages=f"{Path(Path(__file__).parent.resolve())}{os.path.sep}test-assets") helpers.run_e2e(gui) assert ".taipy-text" in urlopen( f"http://127.0.0.1:{e2e_port}{e2e_base_url}test-assets/style/style.css" ).read().decode("utf-8") page.goto("./test-assets/page1") page.expect_websocket() page.wait_for_selector("#text1") retry = 0 while ( retry < 10 and page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') != "rgb(0, 128, 0)" ): retry += 1 time.sleep(0.1) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') == "rgb(0, 128, 0)" ) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text2"), null).getPropertyValue("color")') == "rgb(0, 0, 255)" ) @pytest.mark.teste2e def test_html_render_path_mapping(page: "Page", gui: Gui, helpers, e2e_base_url, e2e_port): gui._server = _Server( gui, path_mapping={"style": f"{Path(Path(__file__).parent.resolve())}{os.path.sep}test-assets{os.path.sep}style"}, flask=gui._flask, async_mode="gevent", ) gui.add_page("page1", Html(f"{Path(Path(__file__).parent.resolve())}{os.path.sep}page1.html")) helpers.run_e2e(gui) assert ".taipy-text" in urlopen(f"http://127.0.0.1:{e2e_port}{e2e_base_url}/style/style.css").read().decode("utf-8") page.goto("./page1") page.expect_websocket() page.wait_for_selector("#text1") retry = 0 while ( retry < 10 and page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') != "rgb(0, 128, 0)" ): retry += 1 time.sleep(0.1) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') == "rgb(0, 128, 0)" ) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text2"), null).getPropertyValue("color")') == "rgb(0, 0, 255)" )
import inspect import logging from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_markdown_render_with_style(page: "Page", gui: Gui, helpers): markdown_content = """ <|Hey|id=text1|> <|There|id=text2|class_name=custom-text|> """ style = """ .taipy-text { color: green; } .custom-text { color: blue; } """ gui._set_frame(inspect.currentframe()) gui.add_page("page1", markdown_content, style=style) helpers.run_e2e(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#text1") page.wait_for_selector("#Taipy_style", state="attached") function_evaluated = True try: page.wait_for_function( 'window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color") !== "rgb(255, 255, 255)"' ) except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text1"), null).getPropertyValue("color")') == "rgb(0, 128, 0)" ) assert ( page.evaluate('window.getComputedStyle(document.querySelector("#text2"), null).getPropertyValue("color")') == "rgb(0, 0, 255)" )
import inspect import logging from importlib import util import pytest from taipy.gui import Gui if util.find_spec("playwright"): from playwright._impl._page import Page from .assets2_class_scopes.page1 import Page1 from .assets2_class_scopes.page2 import Page2 def helpers_assert_value(page, s1, s2, v1): s1_val = page.input_value("#s1 input") assert str(s1_val).startswith(s1) s2_val = page.input_value("#s2 input") assert str(s2_val).startswith(s2) val1 = page.query_selector("#v1").inner_text() assert str(val1).startswith(v1) @pytest.mark.timeout(300) @pytest.mark.teste2e @pytest.mark.filterwarnings("ignore::Warning") def test_class_scopes_binding(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) operand_1 = 0 # noqa: F841 gui.add_page("page1", Page1()) gui.add_page("page2", Page2()) helpers.run_e2e(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#s1") helpers_assert_value(page, "0", "0", "0") page.fill("#s1 input", "15") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '0'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "15", "0", "15") page.fill("#s2 input", "20") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '15'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "15", "20", "35") page.goto("./page2") page.expect_websocket() page.wait_for_selector("#s1") helpers_assert_value(page, "15", "0", "0") page.fill("#s2 input", "5") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '0'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "15", "5", "75") page.fill("#s1 input", "17") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '75'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "17", "5", "85") page.goto("./page1") page.expect_websocket() page.wait_for_selector("#s1") helpers_assert_value(page, "17", "20", "37") page.click("#btn_reset") try: page.wait_for_function("document.querySelector('#v1').innerText !== '37'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "17", "0", "17")
import inspect import logging from importlib import util import pytest from taipy.gui import Gui if util.find_spec("playwright"): from playwright._impl._page import Page from .assets.page1 import page as page1 from .assets.page2 import page as page2 from .assets.page3 import page as page3 @pytest.mark.timeout(300) @pytest.mark.teste2e def test_page_scopes(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) def on_change(state, var, val, module): if var == "x" and "page3" in module: state.y = val * 10 gui.add_page("page1", page1) gui.add_page("page2", page2) gui.add_page("page3", page3) helpers.run_e2e(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#x1") assert page.query_selector("#x1").inner_text() == "10" assert page.query_selector("#x2").inner_text() == "20" assert page.query_selector("#y1").inner_text() == "20" assert page.query_selector("#y2").inner_text() == "40" page.goto("./page2") page.expect_websocket() page.wait_for_selector("#x1") assert page.query_selector("#x1").inner_text() == "20" assert page.query_selector("#x2").inner_text() == "40" assert page.query_selector("#y1").inner_text() == "10" assert page.query_selector("#y2").inner_text() == "20" page.goto("./page3") page.expect_websocket() page.wait_for_selector("#x1") assert page.query_selector("#x1").inner_text() == "50" assert page.query_selector("#x2").inner_text() == "100" page.goto("./page1") page.expect_websocket() page.wait_for_selector("#x1") page.fill("#xinput", "15") function_evaluated = True try: page.wait_for_function("document.querySelector('#y2').innerText !== '40'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return assert page.query_selector("#x1").inner_text() == "15" assert page.query_selector("#x2").inner_text() == "30" assert page.query_selector("#y1").inner_text() == "45" assert page.query_selector("#y2").inner_text() == "90" page.goto("./page2") page.expect_websocket() page.wait_for_selector("#x1") assert page.query_selector("#x1").inner_text() == "45" assert page.query_selector("#x2").inner_text() == "90" assert page.query_selector("#y1").inner_text() == "15" assert page.query_selector("#y2").inner_text() == "30" page.fill("#xinput", "37") function_evaluated = True try: page.wait_for_function("document.querySelector('#y2').innerText !== '30'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return assert page.query_selector("#x1").inner_text() == "37" assert page.query_selector("#x2").inner_text() == "74" assert page.query_selector("#y1").inner_text() == "185" assert page.query_selector("#y2").inner_text() == "370" page.goto("./page1") page.expect_websocket() page.wait_for_selector("#x1") assert page.query_selector("#x1").inner_text() == "185" assert page.query_selector("#x2").inner_text() == "370" assert page.query_selector("#y1").inner_text() == "37" assert page.query_selector("#y2").inner_text() == "74" page.goto("./page3") page.expect_websocket() page.wait_for_selector("#x1") assert page.query_selector("#x1").inner_text() == "50" assert page.query_selector("#x2").inner_text() == "100"
import inspect import logging from importlib import util import pytest from taipy.gui import Gui, Markdown if util.find_spec("playwright"): from playwright._impl._page import Page from .assets3.page1 import page as page1 def helpers_assert_text(page, s): val1 = page.query_selector("#t1").inner_text() assert str(val1).startswith(s) # for issue #583 @pytest.mark.teste2e @pytest.mark.filterwarnings("ignore::Warning") def test_page_scopes_main_var_access(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) n = "Hello" # noqa: F841 root_md = Markdown( """ <|{n}|input|id=i1|> """ ) gui.add_pages({"/": root_md, "page1": page1}) helpers.run_e2e(gui) page.goto("./") page.expect_websocket() page.wait_for_selector("#t1") page.wait_for_selector("#i1") helpers_assert_text(page, "Hello") page.fill("#i1", "Hello World") function_evaluated = True try: page.wait_for_function("document.querySelector('#t1').innerText !== 'Hello'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_text(page, "Hello World")
# # 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 inspect import logging from importlib import util import pytest from taipy.gui import Gui, Markdown if util.find_spec("playwright"): from playwright._impl._page import Page from .assets3_class_scopes.page1 import Page1 def helpers_assert_text(page, s): val1 = page.query_selector("#t1").inner_text() assert str(val1).startswith(s) # for issue #583 @pytest.mark.teste2e @pytest.mark.filterwarnings("ignore::Warning") def test_class_scopes_main_var_access(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) n = "Hello" # noqa: F841 root_md = Markdown( """ <|{n}|input|id=i1|> """ ) gui.add_pages({"/": root_md, "page1": Page1()}) helpers.run_e2e(gui) page.goto("./") page.expect_websocket() page.wait_for_selector("#t1") page.wait_for_selector("#i1") helpers_assert_text(page, "Hello") page.fill("#i1", "Hello World") function_evaluated = True try: page.wait_for_function("document.querySelector('#t1').innerText !== 'Hello'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_text(page, "Hello World")
import inspect import logging from importlib import util import pytest from taipy.gui import Gui if util.find_spec("playwright"): from playwright._impl._page import Page from .assets4.page1 import page as page1 from .assets4.page1 import reset_d @pytest.mark.timeout(300) @pytest.mark.teste2e @pytest.mark.filterwarnings("ignore::Warning") def test_page_scopes_state_runtime(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) def test(state): reset_d(state) def test2(state): state["page1"].d = 30 page_md = """ <|button|on_action=test|id=btn1|> <|button|on_action=test2|id=btn2|> """ gui.add_page("page1", page1) gui.add_page(name=Gui._get_root_page_name(), page=page_md) helpers.run_e2e(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#n1") text1 = page.query_selector("#t1") assert text1.inner_text() == "20" page.fill("#n1", "21") function_evaluated = True try: page.wait_for_function("document.querySelector('#t1').innerText !== '20'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return text1 = page.query_selector("#t1") assert text1.inner_text() == "21" page.click("#btn1") try: page.wait_for_function("document.querySelector('#t1').innerText !== '21'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return text1 = page.query_selector("#t1") assert text1.inner_text() == "20" page.click("#btn2") try: page.wait_for_function("document.querySelector('#t1').innerText !== '20'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return text1 = page.query_selector("#t1") assert text1.inner_text() == "30"
import inspect import logging from importlib import util import pytest from taipy.gui import Gui if util.find_spec("playwright"): from playwright._impl._page import Page from .assets2.page1 import page as page1 from .assets2.page2 import page as page2 def helpers_assert_value(page, s1, s2, v1): s1_val = page.input_value("#s1 input") assert str(s1_val).startswith(s1) s2_val = page.input_value("#s2 input") assert str(s2_val).startswith(s2) val1 = page.query_selector("#v1").inner_text() assert str(val1).startswith(v1) @pytest.mark.timeout(300) @pytest.mark.teste2e @pytest.mark.filterwarnings("ignore::Warning") def test_page_scopes_binding(page: "Page", gui: Gui, helpers): gui._set_frame(inspect.currentframe()) operand_1 = 0 # noqa: F841 gui.add_page("page1", page1) gui.add_page("page2", page2) helpers.run_e2e(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#s1") helpers_assert_value(page, "0", "0", "0") page.fill("#s1 input", "15") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '0'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "15", "0", "15") page.fill("#s2 input", "20") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '15'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "15", "20", "35") page.goto("./page2") page.expect_websocket() page.wait_for_selector("#s1") helpers_assert_value(page, "15", "0", "0") page.fill("#s2 input", "5") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '0'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "15", "5", "75") page.fill("#s1 input", "17") function_evaluated = True try: page.wait_for_function("document.querySelector('#v1').innerText !== '75'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return helpers_assert_value(page, "17", "5", "85") page.goto("./page1") page.expect_websocket() page.wait_for_selector("#s1") helpers_assert_value(page, "17", "20", "37")
from taipy.gui import Markdown, Page class Page1(Page): def __init__(self): self.operand_2 = 0 super().__init__() def create_page(self): return Markdown("page1.md") def reset(state): state.operand_2 = 0
# # 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 taipy.gui import Markdown, Page class Page2(Page): def __init__(self): self.operand_2 = 0 super().__init__() def create_page(self): return Markdown("page2.md")
from taipy.gui import Markdown, Page class Page1(Page): def create_page(self): return Markdown( """ <|{n}|id=t1|> """ )
# # 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 taipy.gui import Markdown x = 10 y = 20 def on_change(state, var, val): if var == "x": state.y = val * 3 page = Markdown( """ x = <|{x}|id=x1|> x * 2 = <|{x*2}|id=x2|> x number: <|{x}|number|id=xinput|> y = <|{y}|id=y1|> y * 2 = <|{y*2}|id=y2|> """ )
# # 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 taipy.gui import Markdown from .page1 import x as y from .page1 import y as x def on_change(state, var, val): if var == "x": state.y = val * 5 page = Markdown( """ y = <|{x}|id=x1|> y * 2 = <|{x*2}|id=x2|> y number: <|{x}|number|id=xinput|> x = <|{y}|id=y1|> x * 2 = <|{y*2}|id=y2|> """ )
from taipy.gui import Markdown x = 50 page = Markdown( """ <|{x}|id=x1|> x * 2 = <|{x*2}|id=x2|> <|{x}|number|id=xinput|> """ )
from taipy.gui import Markdown page = Markdown( """ # Page1 - Add Operand 1: <|{operand_1}|slider|id=s1|> Operand 2: <|{operand_2}|slider|id=s2|> Operand 1 + Operand 2 = <|{operand_1 + operand_2}|id=v1|> """ ) operand_2 = 0
# # 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 taipy.gui import Markdown page = Markdown( """ # Page2 - Multiply Operand 1: <|{operand_1}|slider|id=s1|> Operand 2: <|{operand_2}|slider|id=s2|> Operand 1 * Operand 2 = <|{operand_1 * operand_2}|id=v1|> """ ) operand_2 = 0
from taipy.gui import Markdown d = 20 def reset_d(state): state.d = d # a page = Markdown( """ <|{d}|text|id=t1|> <|{d}|number|id=n1|> """ )
# # 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 taipy.gui import Markdown page = Markdown( """ <|{n}|id=t1|> """ )
# # 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 inspect import logging from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_slider_action(page: "Page", gui: Gui, helpers): page_md = """ <|{x}|id=text1|> <|{x}|slider|id=slider1|> """ x = 10 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() == "10" page.wait_for_selector("#slider1") page.fill("#slider1 input", "20") function_evaluated = True try: page.wait_for_function("document.querySelector('#text1').innerText !== '10'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: text1_2 = page.query_selector("#text1") assert text1_2.inner_text() == "20" @pytest.mark.teste2e def test_slider_action_on_change(page: "Page", gui: Gui, helpers): d = {"v1": 10, "v2": 10} # noqa: F841 def on_change(state, var, val): if var == "d.v2": d = {"v1": 2 * val} state.d.update(d) page_md = """ Value: <|{d.v1}|id=text1|> Slider: <|{d.v2}|slider|id=slider1|> """ gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() == "10" page.wait_for_selector("#slider1") page.fill("#slider1 input", "20") function_evaluated = True try: page.wait_for_function("document.querySelector('#text1').innerText !== '10'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: text1_2 = page.query_selector("#text1") assert text1_2.inner_text() == "40"
import inspect import logging from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_button_action(page: "Page", gui: Gui, helpers): page_md = """ <|{x}|id=text1|> <|Action|button|on_action=do_something_fn|id=button1|> """ x = 10 # noqa: F841 def do_something_fn(state): state.x = state.x * 2 gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() == "10" page.click("#button1") function_evaluated = True try: page.wait_for_function("document.querySelector('#text1').innerText !== '10'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: text1_2 = page.query_selector("#text1") assert text1_2.inner_text() == "20"
import inspect import time from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui, State @pytest.mark.teste2e def test_selector_action(page: "Page", gui: Gui, helpers): page_md = """ <|{x}|selector|lov=Item 1;Item 2;Item 3|id=selector1|> """ x = "Item 1" # noqa: F841 def on_init(state: State): assert state.x == "Item 1" def on_change(state: State, var, val): if var == "x": assert val == "Item 3" gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("ul#selector1") page.click('#selector1 > div[data-id="Item 3"]') page.wait_for_function( "document.querySelector('#selector1 > div[data-id=\"Item 3\"]').classList.contains('Mui-selected')" )
import inspect import logging from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui def edit_and_assert_page(page: "Page"): assert_input(page, "0") page.fill("#input2 input", "20") function_evaluated = True try: page.wait_for_function("document.querySelector('#val1').innerText !== '0'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return assert_input(page, "20") page.fill("#input1", "30") function_evaluated = True try: page.wait_for_function("document.querySelector('#val1').innerText !== '20'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if not function_evaluated: return assert_input(page, "30") def assert_input(page: "Page", val: str): val1 = page.query_selector("#val1").inner_text() assert str(val1).startswith(val) val2 = page.query_selector("#val2").inner_text() assert str(val2).startswith(f"Val: {val}") inp1 = page.input_value("input#input1") assert str(inp1).startswith(val) inp2 = page.input_value("#input2 input") assert str(inp2).startswith(val) @pytest.mark.filterwarnings("ignore::Warning") @pytest.mark.teste2e def test_slider_input_reload(page: "Page", gui: Gui, helpers): page_md = """ #Test Multi Number <|{val}|id=val1|> <|Val: {val}|id=val2|> <|{val}|number|id=input1|> <|{val}|slider|id=input2|> """ val = 0 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page(name="page1", page=page_md) helpers.run_e2e_multi_client(gui) page.goto("./page1") page.expect_websocket() page.wait_for_selector("#val1") edit_and_assert_page(page) page.reload() page.expect_websocket() page.wait_for_selector("#val1") assert_input(page, "30") page.evaluate("window.localStorage.removeItem('TaipyClientId')") page.reload() page.expect_websocket() page.wait_for_selector("#val1") assert_input(page, "0")
import inspect import logging from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_dict(page: "Page", gui: Gui, helpers): page_md = """ <|{a_dict[a_key]}|input|id=inp1|> <|{a_dict.key}|input|id=inp2|> <|test|button|on_action=on_action_1|id=btn1|> <|test|button|on_action=on_action_2|id=btn2|> """ a_key = "key" a_dict = {a_key: "Taipy"} # noqa: F841 def on_action_1(state): state.a_dict.key = "Hello" def on_action_2(state): state.a_dict[state.a_key] = "World" gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#inp1") assert_text(page, "Taipy", "Taipy") page.fill("input#inp1", "Taipy is the best") function_evaluated = True try: page.wait_for_function("document.querySelector('#inp2').value !== 'Taipy'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: assert_text(page, "Taipy is the best", "Taipy is the best") page.fill("#inp2", "Taipy-Gui") function_evaluated = True try: page.wait_for_function("document.querySelector('#inp1').value !== 'Taipy is the best'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: assert_text(page, "Taipy-Gui", "Taipy-Gui") page.click("#btn1") function_evaluated = True try: page.wait_for_function("document.querySelector('#inp1').value !== 'Taipy-Gui'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: assert_text(page, "Hello", "Hello") page.click("#btn2") function_evaluated = True try: page.wait_for_function("document.querySelector('#inp1').value !== 'Hello'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: assert_text(page, "World", "World") def assert_text(page, inp1, inp2): assert page.input_value("input#inp1") == inp1 assert page.input_value("input#inp2") == inp2
import inspect import logging from importlib import util import pytest if util.find_spec("playwright"): from playwright._impl._page import Page from taipy.gui import Gui @pytest.mark.teste2e def test_text_edit(page: "Page", gui: Gui, helpers): page_md = """ <|{x}|text|id=text1|> <|{x}|input|id=input1|> """ x = "Hey" # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() == "Hey" page.wait_for_selector("#input1") page.fill("#input1", "There") function_evaluated = True try: page.wait_for_function("document.querySelector('#text1').innerText !== 'Hey'") except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: text1_2 = page.query_selector("#text1") assert text1_2.inner_text() == "There" @pytest.mark.teste2e def test_number_edit(page: "Page", gui: Gui, helpers): page_md = """ <|{x}|text|id=text1|> <|{x}|number|id=number1|> """ x = 10 # noqa: F841 gui._set_frame(inspect.currentframe()) gui.add_page(name="test", page=page_md) helpers.run_e2e(gui) page.goto("./test") page.expect_websocket() page.wait_for_selector("#text1") text1 = page.query_selector("#text1") assert text1.inner_text() == "10" page.wait_for_selector("#number1") page.fill("#number1", "20") function_evaluated = True try: page.wait_for_function("document.querySelector('#text1').innerText !== '10'") function_evaluated = True except Exception as e: function_evaluated = False logging.getLogger().debug(f"Function evaluation timeout.\n{e}") if function_evaluated: text1_2 = page.query_selector("#text1") assert text1_2.inner_text() == "20"
from importlib import util from taipy.gui import Gui from taipy.gui.data.array_dict_data_accessor import _ArrayDictDataAccessor from taipy.gui.data.data_format import _DataFormat from taipy.gui.utils import _MapDict an_array = [1, 2, 3] def test_simple_data(gui: Gui, helpers): accessor = _ArrayDictDataAccessor() ret_data = accessor.get_data(gui, "x", an_array, {"start": 0, "end": -1}, _DataFormat.JSON) assert ret_data value = ret_data["value"] assert value assert value["rowcount"] == 3 data = value["data"] assert len(data) == 3 def test_simple_data_with_arrow(gui: Gui, helpers): if util.find_spec("pyarrow"): accessor = _ArrayDictDataAccessor() ret_data = accessor.get_data(gui, "x", an_array, {"start": 0, "end": -1}, _DataFormat.APACHE_ARROW) assert ret_data value = ret_data["value"] assert value assert value["rowcount"] == 3 data = value["data"] assert isinstance(data, bytes) def test_slice(gui: Gui, helpers): accessor = _ArrayDictDataAccessor() value = accessor.get_data(gui, "x", an_array, {"start": 0, "end": 1}, _DataFormat.JSON)["value"] assert value["rowcount"] == 3 data = value["data"] assert len(data) == 2 value = accessor.get_data(gui, "x", an_array, {"start": "0", "end": "1"}, _DataFormat.JSON)["value"] data = value["data"] assert len(data) == 2 def test_sort(gui: Gui, helpers): accessor = _ArrayDictDataAccessor() a_dict = {"name": ["A", "B", "C"], "value": [3, 2, 1]} query = {"columns": ["name", "value"], "start": 0, "end": -1, "orderby": "name", "sort": "desc"} data = accessor.get_data(gui, "x", a_dict, query, _DataFormat.JSON)["value"]["data"] assert data[0]["name"] == "C" def test_aggregate(gui: Gui, helpers, small_dataframe): accessor = _ArrayDictDataAccessor() a_dict = {"name": ["A", "B", "C", "A"], "value": [3, 2, 1, 2]} query = {"columns": ["name", "value"], "start": 0, "end": -1, "aggregates": ["name"], "applies": {"value": "sum"}} value = accessor.get_data(gui, "x", a_dict, query, _DataFormat.JSON)["value"] assert value["rowcount"] == 3 data = value["data"] agregValue = next(v.get("value") for v in data if v.get("name") == "A") assert agregValue == 5 def test_array_of_array(gui: Gui, helpers, small_dataframe): accessor = _ArrayDictDataAccessor() an_array = [[1, 2, 3], [2, 4, 6]] ret_data = accessor.get_data(gui, "x", an_array, {"start": 0, "end": -1}, _DataFormat.JSON) assert ret_data value = ret_data["value"] assert value assert value["rowcount"] == 2 data = value["data"] assert len(data) == 2 assert len(data[0]) == 4 # including _tp_index def test_empty_array(gui: Gui, helpers, small_dataframe): accessor = _ArrayDictDataAccessor() an_array: list[str] = [] ret_data = accessor.get_data(gui, "x", an_array, {"start": 0, "end": -1}, _DataFormat.JSON) assert ret_data value = ret_data["value"] assert value assert value["rowcount"] == 0 data = value["data"] assert len(data) == 0 def test_array_of_diff_array(gui: Gui, helpers, small_dataframe): accessor = _ArrayDictDataAccessor() an_array = [[1, 2, 3], [2, 4]] ret_data = accessor.get_data(gui, "x", an_array, {"start": 0, "end": -1, "alldata": True}, _DataFormat.JSON) assert ret_data value = ret_data["value"] assert value assert value["multi"] is True data = value["data"] assert len(data) == 2 assert len(data[0]["0/0"]) == 3 assert len(data[1]["1/0"]) == 2 def test_array_of_dicts(gui: Gui, helpers, small_dataframe): accessor = _ArrayDictDataAccessor() an_array_of_dicts = [ { "temperatures": [ [17.2, 27.4, 28.6, 21.5], [5.6, 15.1, 20.2, 8.1], [26.6, 22.8, 21.8, 24.0], [22.3, 15.5, 13.4, 19.6], [3.9, 18.9, 25.7, 9.8], ], "cities": ["Hanoi", "Paris", "Rio de Janeiro", "Sydney", "Washington"], }, {"seasons": ["Winter", "Summer", "Spring", "Autumn"]}, ] ret_data = accessor.get_data( gui, "x", an_array_of_dicts, {"start": 0, "end": -1, "alldata": True}, _DataFormat.JSON ) assert ret_data value = ret_data["value"] assert value assert value["multi"] is True data = value["data"] assert len(data) == 2 assert len(data[0]["temperatures"]) == 5 assert len(data[1]["seasons"]) == 4 def test_array_of_Mapdicts(gui: Gui, helpers, small_dataframe): accessor = _ArrayDictDataAccessor() dict1 = _MapDict( { "temperatures": [ [17.2, 27.4, 28.6, 21.5], [5.6, 15.1, 20.2, 8.1], [26.6, 22.8, 21.8, 24.0], [22.3, 15.5, 13.4, 19.6], [3.9, 18.9, 25.7, 9.8], ], "cities": ["Hanoi", "Paris", "Rio de Janeiro", "Sydney", "Washington"], } ) dict2 = _MapDict({"seasons": ["Winter", "Summer", "Spring", "Autumn"]}) ret_data = accessor.get_data(gui, "x", [dict1, dict2], {"start": 0, "end": -1, "alldata": True}, _DataFormat.JSON) assert ret_data value = ret_data["value"] assert value assert value["multi"] is True data = value["data"] assert len(data) == 2 assert len(data[0]["temperatures"]) == 5 assert len(data[1]["seasons"]) == 4
import inspect import taipy.gui.builder as tgb from taipy.gui import Gui def test_slider_builder(gui: Gui, test_client, helpers): gui._bind_var_val("x", 10) with tgb.Page(frame=None) as page: tgb.slider(value="{x}") expected_list = [ "<Slider", 'updateVarName="_TpN_tpec_TpExPr_x_TPMDL_0', "defaultValue={10}", "value={_TpN_tpec_TpExPr_x_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_slider_with_min_max_builder(gui: Gui, test_client, helpers): gui._bind_var_val("x", 0) with tgb.Page(frame=None) as page: tgb.slider(value="{x}", min=-10, max=10) expected_list = ["<Slider", "min={-10.0}", "max={10.0}", "defaultValue={0}"] helpers.test_control_builder(gui, page, expected_list) def test_slider_with_dict_labels_builder(gui: Gui, helpers): sel = "Item 1" # noqa: F841 labels = {"Item 1": "Label Start", "Item 3": "Label End"} # noqa: F841 gui._set_frame(inspect.currentframe()) with tgb.Page(frame=None) as page: tgb.slider(value="{sel}", lov="Item 1;Item 2;Item 3", labels=labels) expected_list = [ "<Slider", 'labels="{&quot;Item 1&quot;: &quot;Label Start&quot;, &quot;Item 3&quot;: &quot;Label End&quot;}"', ] helpers.test_control_builder(gui, page, expected_list) def test_slider_with_boolean_labels_builder(gui: Gui, helpers): sel = "Item 1" # noqa: F841 gui._set_frame(inspect.currentframe()) with tgb.Page(frame=None) as page: tgb.slider(value="{sel}", lov="Item 1;Item 2;Item 3", labels=True) expected_list = ["<Slider", "labels={true}"] helpers.test_control_builder(gui, page, expected_list) def test_slider_items_builder(gui: Gui, test_client, helpers): gui._bind_var_val("x", "Item 1") with tgb.Page(frame=None) as page: tgb.slider(value="{x}", lov="Item 1;Item 2;Item 3", text_anchor="left") expected_list = [ "<Slider", 'updateVarName="_TpLv_tpec_TpExPr_x_TPMDL_0"', "value={_TpLv_tpec_TpExPr_x_TPMDL_0}", 'defaultLov="[&quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;]"', 'defaultValue="[&quot;Item 1&quot;]"', 'textAnchor="left"', ] helpers.test_control_builder(gui, page, expected_list) def test_slider_text_anchor_builder(gui: Gui, test_client, helpers): gui._bind_var_val("x", "Item 1") with tgb.Page(frame=None) as page: tgb.slider(value="{x}", text_anchor=None) expected_list = [ "<Slider", 'updateVarName="_TpN_tpec_TpExPr_x_TPMDL_0"', "value={_TpN_tpec_TpExPr_x_TPMDL_0}", 'textAnchor="none"', ] helpers.test_control_builder(gui, page, expected_list) def test_slider_text_anchor_default_builder(gui: Gui, test_client, helpers): gui._bind_var_val("x", "Item 1") with tgb.Page(frame=None) as page: tgb.slider(value="{x}", items="Item 1") expected_list = [ "<Slider", 'updateVarName="_TpN_tpec_TpExPr_x_TPMDL_0"', "value={_TpN_tpec_TpExPr_x_TPMDL_0}", 'textAnchor="bottom"', ] helpers.test_control_builder(gui, page, expected_list)
# # 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 taipy.gui.builder as tgb from taipy.gui import Gui def test_button_builder_1(gui: Gui, test_client, helpers): gui._bind_var_val("name", "World!") gui._bind_var_val("btn_id", "button1") with tgb.Page(frame=None) as page: tgb.button(label="Hello {name}", id="{btn_id}") expected_list = ["<Button", 'defaultLabel="Hello World!"', "label={tp_TpExPr_Hello_name_TPMDL_0_0"] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_selector_builder_1(gui: Gui, test_client, helpers): gui._bind_var_val("selected_val", ["l1", "l2"]) gui._bind_var_val("selector_properties", {"lov": [("l1", "v1"), ("l2", "v2"), ("l3", "v3")], "filter": True}) with tgb.Page(frame=None) as page: tgb.selector(value="{selected_val}", properties="{selector_properties}", multiple=True) expected_list = [ "<Selector", 'defaultLov="[[&quot;l1&quot;, &quot;v1&quot;], [&quot;l2&quot;, &quot;v2&quot;], [&quot;l3&quot;, &quot;v3&quot;]]"', 'defaultValue="[&quot;l1&quot;, &quot;l2&quot;]"', "filter={true}", "multiple={true}", 'updateVarName="_TpLv_tpec_TpExPr_selected_val_TPMDL_0"', "value={_TpLv_tpec_TpExPr_selected_val_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_selector_builder_2(gui: Gui, test_client, helpers): gui._bind_var_val("selected_val", "Item 2") with tgb.Page(frame=None) as page: tgb.selector(value="{selected_val}", lov="Item 1;Item 2; This is a another value") expected_list = [ "<Selector", 'defaultLov="[&quot;Item 1&quot;, &quot;Item 2&quot;, &quot; This is a another value&quot;]"', 'defaultValue="[&quot;Item 2&quot;]"', 'updateVarName="_TpLv_tpec_TpExPr_selected_val_TPMDL_0"', "value={_TpLv_tpec_TpExPr_selected_val_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_selector_builder_3(gui: Gui, test_client, helpers): gui._bind_var_val("elt", None) gui._bind_var_val( "scenario_list", [{"id": "1", "name": "scenario 1"}, {"id": "3", "name": "scenario 3"}, {"id": "2", "name": "scenario 2"}], ) gui._bind_var_val("selected_obj", {"id": "1", "name": "scenario 1"}) with tgb.Page(frame=None) as page: tgb.selector( value="{selected_obj}", lov="{scenario_list}", adapter="{lambda elt: (elt['id'], elt['name'])}", propagate=False, ) expected_list = [ "<Selector", 'defaultLov="[[&quot;1&quot;, &quot;scenario 1&quot;], [&quot;3&quot;, &quot;scenario 3&quot;], [&quot;2&quot;, &quot;scenario 2&quot;]]"', 'defaultValue="[&quot;1&quot;]"', "lov={_TpL_tpec_TpExPr_scenario_list_TPMDL_0}", "propagate={false}", 'updateVars="lov=_TpL_tpec_TpExPr_scenario_list_TPMDL_0"', 'updateVarName="_TpLv_tpec_TpExPr_selected_obj_TPMDL_0"', "value={_TpLv_tpec_TpExPr_selected_obj_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list)
import inspect import taipy.gui.builder as tgb from taipy.gui import Gui def test_input_builder(gui: Gui, helpers): x = "Hello World!" # noqa: F841 gui._set_frame(inspect.currentframe()) with tgb.Page(frame=None) as page: tgb.input(value="{x}") expected_list = [ "<Input", 'updateVarName="tpec_TpExPr_x_TPMDL_0"', 'defaultValue="Hello World!"', 'type="text"', "value={tpec_TpExPr_x_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_password_builder(gui: Gui, helpers): x = "Hello World!" # noqa: F841 gui._set_frame(inspect.currentframe()) with tgb.Page(frame=None) as page: tgb.input(value="{x}", password=True) expected_list = [ "<Input", 'updateVarName="tpec_TpExPr_x_TPMDL_0"', 'defaultValue="Hello World!"', 'type="password"', "value={tpec_TpExPr_x_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_tree_builder(gui: Gui, test_client, helpers): gui._bind_var_val("value", "Item 1") with tgb.Page(frame=None) as page: tgb.tree(value="{value}", lov="Item 1;Item 2;Item 3") expected_list = [ "<TreeView", 'defaultLov="[&quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;]"', 'defaultValue="[&quot;Item 1&quot;]"', 'updateVarName="_TpLv_tpec_TpExPr_value_TPMDL_0"', "value={_TpLv_tpec_TpExPr_value_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_tree_expanded_builder_1(gui: Gui, test_client, helpers): gui._bind_var_val("value", "Item 1") with tgb.Page(frame=None) as page: tgb.tree(value="{value}", lov="Item 1;Item 2;Item 3", expanded=False) expected_list = [ "<TreeView", 'defaultLov="[&quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;]"', 'defaultValue="[&quot;Item 1&quot;]"', 'updateVarName="_TpLv_tpec_TpExPr_value_TPMDL_0"', "value={_TpLv_tpec_TpExPr_value_TPMDL_0}", "expanded={false}", ] helpers.test_control_builder(gui, page, expected_list) def test_tree_expanded_builder_2(gui: Gui, test_client, helpers): gui._bind_var_val("value", "Item 1") gui._bind_var_val("expa", ["Item1"]) with tgb.Page(frame=None) as page: tgb.tree(value="{value}", lov="Item 1;Item 2;Item 3", expanded="{expa}") expected_list = [ "<TreeView", 'defaultLov="[&quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;]"', 'defaultValue="[&quot;Item 1&quot;]"', 'updateVarName="_TpLv_tpec_TpExPr_value_TPMDL_0"', "value={_TpLv_tpec_TpExPr_value_TPMDL_0}", 'defaultExpanded="[&quot;Item1&quot;]"', "expanded={tpec_TpExPr_expa_TPMDL_0}", 'updateVars="expanded=tpec_TpExPr_expa_TPMDL_0', ] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_expandable_builder_1(gui: Gui, helpers): with tgb.expandable(title="Expandable section", expanded=False) as content: tgb.text(value="This is an expandable section") expected_list = [ "<Expandable", "expanded={false}", 'title="Expandable section"', "This is an expandable section", ] helpers.test_control_builder(gui, tgb.Page(content, frame=None), expected_list)
import inspect import taipy.gui.builder as tgb from taipy.gui import Gui def test_table_builder_1(gui: Gui, helpers, csvdata): with tgb.Page(frame=None) as page: tgb.table( data="{csvdata}", page_size=10, page_size_options=[10, 30, 100], columns=["Day", "Entity", "Code", "Daily hospital occupancy"], date_format="eee dd MMM yyyy", ) expected_list = [ "<Table", 'defaultColumns="{&quot;Entity&quot;: &#x7B;&quot;index&quot;: 1, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Entity&quot;&#x7D;, &quot;Code&quot;: &#x7B;&quot;index&quot;: 2, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Code&quot;&#x7D;, &quot;Daily hospital occupancy&quot;: &#x7B;&quot;index&quot;: 3, &quot;type&quot;: &quot;int&quot;, &quot;dfid&quot;: &quot;Daily hospital occupancy&quot;&#x7D;, &quot;Day_str&quot;: &#x7B;&quot;index&quot;: 0, &quot;type&quot;: &quot;datetime&quot;, &quot;dfid&quot;: &quot;Day&quot;, &quot;format&quot;: &quot;eee dd MMM yyyy&quot;&#x7D;}"', 'height="80vh"', 'width="100%"', 'pageSizeOptions="[10, 30, 100]"', "pageSize={10.0}", "selected={[]}", 'updateVarName="_TpD_tpec_TpExPr_csvdata_TPMDL_0"', "data={_TpD_tpec_TpExPr_csvdata_TPMDL_0}", ] gui._set_frame(inspect.currentframe()) helpers.test_control_builder(gui, page, expected_list) def test_table_reset_builder(gui: Gui, helpers, csvdata): with tgb.Page(frame=None) as page: tgb.table( data="{csvdata}", rebuild=True, page_size=10, page_size_options="10;30;100", columns="Day;Entity;Code;Daily hospital occupancy", date_format="eee dd MMM yyyy", ) expected_list = [ "<Table", 'defaultColumns="{&quot;Entity&quot;: &#x7B;&quot;index&quot;: 1, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Entity&quot;&#x7D;, &quot;Code&quot;: &#x7B;&quot;index&quot;: 2, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Code&quot;&#x7D;, &quot;Daily hospital occupancy&quot;: &#x7B;&quot;index&quot;: 3, &quot;type&quot;: &quot;int&quot;, &quot;dfid&quot;: &quot;Daily hospital occupancy&quot;&#x7D;, &quot;Day_str&quot;: &#x7B;&quot;index&quot;: 0, &quot;type&quot;: &quot;datetime&quot;, &quot;dfid&quot;: &quot;Day&quot;, &quot;format&quot;: &quot;eee dd MMM yyyy&quot;&#x7D;}"', 'height="80vh"', 'width="100%"', 'pageSizeOptions="[10, 30, 100]"', "pageSize={10.0}", "selected={[]}", 'updateVarName="_TpD_tpec_TpExPr_csvdata_TPMDL_0"', "data={_TpD_tpec_TpExPr_csvdata_TPMDL_0}", "columns={tp_TpExPr_gui_tbl_cols_True_None_7B_22columns_22_3A_20_22Day_3BEntity_3BCode_3BDaily_20hospital_20occupancy_22_2C_20_22date_format_22_3A_20_22eee_20dd_20MMM_20yyyy_22_7D_7B_22data_22_3A_20_22tpec_TpExPr_csvdata_TPMDL_0_22_7D_tpec_TpExPr_csvdata_TPMDL_0_csvdata_TPMDL_0_0}", ] gui._set_frame(inspect.currentframe()) helpers.test_control_builder(gui, page, expected_list) def test_table_builder_2(gui: Gui, helpers, csvdata): table_properties = { # noqa: F841 "page_size": 10, "page_size_options": [10, 50, 100, 500], "allow_all_rows": True, "columns": { "Day": {"index": 0, "format": "dd/MM/yyyy", "title": "Date of measure"}, "Entity": {"index": 1}, "Code": {"index": 2}, "Daily hospital occupancy": {"index": 3}, }, "date_format": "eee dd MMM yyyy", "number_format": "%.3f", "width": "60vw", "height": "60vh", } with tgb.Page(frame=None) as page: tgb.table(data="{csvdata}", properties="table_properties", auto_loading=True, editable=False) expected_list = [ "<Table", "allowAllRows={true}", "autoLoading={true}", "editable={false}", 'defaultColumns="{&quot;Entity&quot;: &#x7B;&quot;index&quot;: 1, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Entity&quot;&#x7D;, &quot;Code&quot;: &#x7B;&quot;index&quot;: 2, &quot;type&quot;: &quot;object&quot;, &quot;dfid&quot;: &quot;Code&quot;&#x7D;, &quot;Daily hospital occupancy&quot;: &#x7B;&quot;index&quot;: 3, &quot;type&quot;: &quot;int&quot;, &quot;dfid&quot;: &quot;Daily hospital occupancy&quot;, &quot;format&quot;: &quot;%.3f&quot;&#x7D;, &quot;Day_str&quot;: &#x7B;&quot;index&quot;: 0, &quot;format&quot;: &quot;dd/MM/yyyy&quot;, &quot;title&quot;: &quot;Date of measure&quot;, &quot;type&quot;: &quot;datetime&quot;, &quot;dfid&quot;: &quot;Day&quot;&#x7D;}"', 'height="60vh"', 'width="60vw"', 'pageSizeOptions="[10, 50, 100, 500]"', "pageSize={10}", "selected={[]}", 'updateVarName="_TpD_tpec_TpExPr_csvdata_TPMDL_0"', "data={_TpD_tpec_TpExPr_csvdata_TPMDL_0}", ] gui._set_frame(inspect.currentframe()) helpers.test_control_builder(gui, page, expected_list)
import os import pathlib from importlib import util import taipy.gui.builder as tgb from taipy.gui import Gui def test_image_url_builder(gui: Gui, test_client, helpers): gui._bind_var_val("content", "some_url") with tgb.Page(frame=None) as page: tgb.image(content="{content}") expected_list = [ "<Image", "content={_TpCi_tpec_TpExPr_content_TPMDL_0}", 'defaultContent="some_url"', ] helpers.test_control_builder(gui, page, expected_list) def test_image_file_builder(gui: Gui, test_client, helpers): with open((pathlib.Path(__file__).parent.parent.parent / "resources" / "fred.png").resolve(), "rb") as content: gui._bind_var_val("content", content.read()) with tgb.Page(frame=None) as page: tgb.image(content="{content}") expected_list = [ "<Image", 'defaultContent="data:image/png;base64,', ] if not util.find_spec("magic"): expected_list = ["<Image", 'defaultContent="/taipy-content/taipyStatic0/TaiPyContent.', ".bin"] helpers.test_control_builder(gui, page, expected_list) def test_image_path_builder(gui: Gui, test_client, helpers): gui._bind_var_val( "content", str((pathlib.Path(__file__).parent.parent.parent / "resources" / "fred.png").resolve()) ) with tgb.Page(frame=None) as page: tgb.image(content="{content}") expected_list = [ "<Image", 'defaultContent="/taipy-content/taipyStatic0/fred.png', ] helpers.test_control_builder(gui, page, expected_list) def test_image_bad_file_builder(gui: Gui, test_client, helpers): with open(os.path.abspath(__file__), "rb") as content: gui._bind_var_val("content", content.read()) with tgb.Page(frame=None) as page: tgb.image(content="{content}") expected_list = [ "<Image", 'defaultContent="Invalid content: text/x', ] if not util.find_spec("magic"): expected_list = ["<Image", 'defaultContent="/taipy-content/taipyStatic0/TaiPyContent.', ".bin"] helpers.test_control_builder(gui, page, expected_list)
# # 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.
# # 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 taipy.gui.builder as tgb from taipy.gui import Gui def test_html_builder(gui: Gui, test_client, helpers): gui._bind_var_val("name", "World!") gui._bind_var_val("btn_id", "button1") with tgb.Page(frame=None) as page: tgb.html("h1", "This is a header", style="color:Tomato;") with tgb.html("p", "This is a paragraph.", style="color:green;"): tgb.html("a", "a text", href="https://www.w3schools.com", target="_blank") tgb.html("br") tgb.html("b", "This is bold text inside the paragrah.") expected_list = [ '<h1 style="color:Tomato;">This is a header', '<p style="color:green;">This is a paragraph.', '<a href="https://www.w3schools.com" target="_blank">a text', "<br>", "<b>This is bold text inside the paragrah.", ] helpers.test_control_builder(gui, page, expected_list)
import inspect import taipy.gui.builder as tgb from taipy.gui import Gui def test_status_builder(gui: Gui, helpers): status = [{"status": "info", "message": "Info Message"}] # noqa: F841 with tgb.Page(frame=None) as page: tgb.status(value="{status}") expected_list = [ "<Status", 'defaultValue="[&#x7B;&quot;status&quot;: &quot;info&quot;, &quot;message&quot;: &quot;Info Message&quot;&#x7D;]"', "value={tpec_TpExPr_status_TPMDL_0}", ] gui._set_frame(inspect.currentframe()) helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_toggle_builder(gui: Gui, helpers): with tgb.Page(frame=None) as page: tgb.toggle(theme=True) expected_list = ["<Toggle", 'kind="theme"', 'unselectedValue=""'] helpers.test_control_builder(gui, page, expected_list) def test_toggle_allow_unselected_builder(gui: Gui, helpers): with tgb.Page(frame=None) as page: tgb.toggle(allow_unselect=True, lov="1;2") expected_list = ["<Toggle", 'unselectedValue=""', "allowUnselect={true}"] helpers.test_control_builder(gui, page, expected_list) def test_toggle_lov_builder(gui: Gui, test_client, helpers): gui._bind_var_val("x", "l1") gui._bind_var_val("lov", [("l1", "v1"), ("l2", "v2")]) with tgb.Page(frame=None) as page: tgb.toggle(lov="{lov}", value="{x}", label="Label") expected_list = [ "<Toggle", 'defaultLov="[[&quot;l1&quot;, &quot;v1&quot;], [&quot;l2&quot;, &quot;v2&quot;]]"', 'defaultValue="l1"', 'label="Label"', "lov={_TpL_tpec_TpExPr_lov_TPMDL_0}", 'updateVars="lov=_TpL_tpec_TpExPr_lov_TPMDL_0"', 'updateVarName="_TpLv_tpec_TpExPr_x_TPMDL_0"', 'unselectedValue=""', "value={_TpLv_tpec_TpExPr_x_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_pane_builder(gui: Gui, test_client, helpers): gui._bind_var_val("show_pane", False) with tgb.Page(frame=None) as page: with tgb.pane(open="{show_pane}"): tgb.text(value="This is a Pane") expected_list = [ "<Pane", 'anchor="left"', 'updateVarName="_TpB_tpec_TpExPr_show_pane_TPMDL_0"', "open={_TpB_tpec_TpExPr_show_pane_TPMDL_0}", "This is a Pane", ] helpers.test_control_builder(gui, page, expected_list) def test_pane_persistent_builder(gui: Gui, test_client, helpers): gui._bind_var_val("show_pane", False) with tgb.Page(frame=None) as page: with tgb.pane(open="{show_pane}", persistent=True): tgb.text(value="This is a Pane") expected_list = [ "<Pane", 'anchor="left"', "persistent={true}", 'updateVarName="_TpB_tpec_TpExPr_show_pane_TPMDL_0"', "open={_TpB_tpec_TpExPr_show_pane_TPMDL_0}", "This is a Pane", ] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_text_builder_1(gui: Gui, test_client, helpers): gui._bind_var_val("x", 10) with tgb.Page(frame=None) as page: tgb.text(value="{x}") expected_list = ["<Field", 'dataType="int"', 'defaultValue="10"', "value={tpec_TpExPr_x_TPMDL_0}"] helpers.test_control_builder(gui, page, expected_list) def test_text_builder_2(gui: Gui, test_client, helpers): gui._bind_var_val("x", 10) with tgb.Page(frame=None) as page: tgb.text("{x}") expected_list = ["<Field", 'dataType="int"', 'defaultValue="10"', "value={tpec_TpExPr_x_TPMDL_0}"] helpers.test_control_builder(gui, page, expected_list)
import os import pathlib from importlib import util import taipy.gui.builder as tgb from taipy.gui import Gui def test_file_download_url_builder(gui: Gui, test_client, helpers): gui._bind_var_val("content", "some_url") with tgb.Page(frame=None) as page: tgb.file_download(content="{content}") expected_list = [ "<FileDownload", "content={_TpC_tpec_TpExPr_content_TPMDL_0}", 'defaultContent="some_url"', ] helpers.test_control_builder(gui, page, expected_list) def test_file_download_file_builder(gui: Gui, test_client, helpers): with open((pathlib.Path(__file__).parent.parent.parent / "resources" / "fred.png").resolve(), "rb") as content: gui._bind_var_val("content", content.read()) with tgb.Page(frame=None) as page: tgb.file_download(content="{content}") expected_list = [ "<FileDownload", 'defaultContent="data:image/png;base64,', ] if not util.find_spec("magic"): expected_list = ["<FileDownload", 'defaultContent="/taipy-content/taipyStatic0/TaiPyContent.', ".bin"] helpers.test_control_builder(gui, page, expected_list) def test_file_download_path_builder(gui: Gui, test_client, helpers): gui._bind_var_val( "content", str((pathlib.Path(__file__).parent.parent.parent / "resources" / "fred.png").resolve()) ) with tgb.Page(frame=None) as page: tgb.file_download(content="{content}") expected_list = [ "<FileDownload", 'defaultContent="/taipy-content/taipyStatic0/fred.png', ] helpers.test_control_builder(gui, page, expected_list) def test_file_download_any_file_builder(gui: Gui, test_client, helpers): with open(os.path.abspath(__file__), "rb") as content: gui._bind_var_val("content", content.read()) with tgb.Page(frame=None) as page: tgb.file_download(content="{content}") expected_list = [ "<FileDownload", 'defaultContent="data:text/x', "python;base64,", ] if not util.find_spec("magic"): expected_list = ["<FileDownload", 'defaultContent="/taipy-content/taipyStatic0/TaiPyContent.', ".bin"] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_file_selector_builder(gui: Gui, test_client, helpers): gui._bind_var_val("content", None) with tgb.Page(frame=None) as page: tgb.file_selector(content="{content}", label="label", on_action="action") expected_list = [ "<FileSelector", 'updateVarName="tpec_TpExPr_content_TPMDL_0"', 'label="label"', 'onAction="action"', ] helpers.test_control_builder(gui, page, expected_list)
import inspect import taipy.gui.builder as tgb from taipy.gui import Gui, Markdown def test_dialog_builder_1(gui: Gui, helpers): dialog_open = False # noqa: F841 gui._set_frame(inspect.currentframe()) with tgb.Page(frame=None) as page: tgb.dialog(title="This is a Dialog", open="{dialog_open}", page="page_test", on_action="validate_action") expected_list = [ "<Dialog", 'onAction="validate_action"', 'page="page_test"', 'title="This is a Dialog"', 'updateVarName="_TpB_tpec_TpExPr_dialog_open_TPMDL_0"', "open={_TpB_tpec_TpExPr_dialog_open_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_dialog_builder_2(gui: Gui, helpers): gui._set_frame(inspect.currentframe()) partial = gui.add_partial(Markdown("# A partial")) # noqa: F841 dialog_open = False # noqa: F841 with tgb.Page(frame=None) as page: tgb.dialog( title="Another Dialog", open="{dialog_open}", partial="{partial}", on_action="validate_action", ) expected_list = [ "<Dialog", 'page="TaiPy_partials', 'title="Another Dialog"', 'onAction="validate_action"', 'updateVarName="_TpB_tpec_TpExPr_dialog_open_TPMDL_0"', "open={_TpB_tpec_TpExPr_dialog_open_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list) def test_dialog_labels_builder(gui: Gui, helpers): gui._set_frame(inspect.currentframe()) dialog_open = False # noqa: F841 with tgb.Page(frame=None) as page: tgb.dialog( title="Another Dialog", open="{dialog_open}", page="page_test", labels=["Cancel", "Validate"], close_label="MYClose", ) expected_list = [ "<Dialog", 'page="page_test"', 'title="Another Dialog"', 'labels="[&quot;Cancel&quot;, &quot;Validate&quot;]"', 'updateVarName="_TpB_tpec_TpExPr_dialog_open_TPMDL_0"', 'closeLabel="MYClose"', "open={_TpB_tpec_TpExPr_dialog_open_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_menu_builder(gui: Gui, test_client, helpers): gui._bind_var_val("lov", ["Item 1", "Item 2", "Item 3", "Item 4"]) with tgb.Page(frame=None) as page: tgb.menu(lov="{lov}", on_action="on_menu_action") expected_list = [ "<MenuCtl", 'libClassName="taipy-menu"', 'defaultLov="[&quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;, &quot;Item 4&quot;]"', "lov={_TpL_tpec_TpExPr_lov_TPMDL_0}", 'onAction="on_menu_action"', 'updateVars="lov=_TpL_tpec_TpExPr_lov_TPMDL_0"', ] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_layout_builder_1(gui: Gui, helpers): with tgb.Page(frame=None) as page: with tgb.layout(columns="1 1", gap="1rem"): tgb.text(value="This is a layout section") expected_list = ["<Layout", 'columns="1 1', 'gap="1rem"', "This is a layout section"] helpers.test_control_builder(gui, page, expected_list)
import taipy.gui.builder as tgb from taipy.gui import Gui def test_number_builder_1(gui: Gui, helpers): with tgb.Page(frame=None) as page: tgb.number(value="10") expected_list = ["<Input", 'value="10"', 'type="number"'] helpers.test_control_builder(gui, page, expected_list) def test_number_builder_2(gui: Gui, test_client, helpers): gui._bind_var_val("x", "10") with tgb.Page(frame=None) as page: tgb.number(value="{x}") expected_list = [ "<Input", 'updateVarName="_TpN_tpec_TpExPr_x_TPMDL_0"', 'defaultValue="10"', 'type="number"', "value={_TpN_tpec_TpExPr_x_TPMDL_0}", ] helpers.test_control_builder(gui, page, expected_list)