import pytest    from taipy.gui import Gui      def test_invalid_control_name(gui: Gui, helpers):      md_string = "<|invalid|invalid|>"      expected_list = ["INVALID SYNTAX - Control is 'invalid'"]      helpers.test_control_md(gui, md_string, expected_list)      def test_value_to_negated_property(gui: Gui, helpers):      md_string = "<|button|not active=true|>"      expected_list = ["<Button", "active={false}"]      helpers.test_control_md(gui, md_string, expected_list)      def test_invalid_property_value(gui: Gui, helpers):      md_string = "<|button|let's try that!|>"      expected_list = ["<Button", 'label="<Empty>"']      helpers.test_control_md(gui, md_string, expected_list)      def test_unclosed_block(gui: Gui, helpers):      md_string = "<|"      expected_list = ["<Part", "</Part>"]      helpers.test_control_md(gui, md_string, expected_list)      def test_opening_unknown_block(gui: Gui, helpers):      md_string = "<|unknown"      expected_list = ["<Part", 'className="unknown"']      helpers.test_control_md(gui, md_string, expected_list)      def test_closing_unknown_block(gui: Gui, helpers):      md_string = "|>"      expected_list = ["
", "No matching opened tag", "
"]      helpers.test_control_md(gui, md_string, expected_list)      def test_md_link(gui: Gui, helpers):      md_string = "[content](link)"      expected_list = ["<a", 'href="link"', "content"]      helpers.test_control_md(gui, md_string, expected_list)


import pytest    from taipy.gui.utils._bindings import _Bindings      def test_exception_binding_twice(gui, test_client):      bind = _Bindings(gui)      bind._new_scopes()      bind._bind("x", 10)      with pytest.raises(ValueError):          bind._bind("x", 10)      def test_exception_binding_invalid_name(gui):      bind = _Bindings(gui)      bind._new_scopes()      with pytest.raises(ValueError):          bind._bind("invalid identifier", 10)


from email import message    import pytest    from taipy.gui._page import _Page      def test_exception_page(gui):      page = _Page()      page._route = "page1"      with pytest.raises(RuntimeError, match="Can't render page page1: no renderer found"):          page.render(gui)


#  # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with  # the License. You may obtain a copy of the License at  #  #        http://www.apache.org/licenses/LICENSE-2.0  #  # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on  # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the  # specific language governing permissions and limitations under the License.


import os  import tempfile  from unittest.mock import patch    import pytest    from taipy.config import Config  from taipy.config._config import _Config  from taipy.config._serializer._toml_serializer import _TomlSerializer  from taipy.config.checker._checker import _Checker  from taipy.config.checker.issue_collector import IssueCollector  from taipy.gui import Gui      class NamedTemporaryFile:      def __init__(self, content=None):          with tempfile.NamedTemporaryFile("w", delete=False) as fd:              if content:                  fd.write(content)              self.filename = fd.name        def read(self):          with open(self.filename, "r") as fp:              return fp.read()        def __del__(self):          os.unlink(self.filename)      def init_config():      Config.unblock_update()      Config._default_config = _Config()._default_config()      Config._python_config = _Config()      Config._file_config = None      Config._env_file_config = None      Config._applied_config = _Config._default_config()      Config._collector = IssueCollector()      Config._serializer = _TomlSerializer()      _Checker._checkers = []        from taipy.config import _inject_section      from taipy.gui._default_config import default_config      from taipy.gui._gui_section import _GuiSection        _inject_section(          _GuiSection,          "gui_config",          _GuiSection(property_list=list(default_config)),          [("configure_gui", _GuiSection._configure)],          add_to_unconflicted_sections=True,      )      @pytest.fixture(scope="function", autouse=True)  def cleanup_test(helpers):      init_config()      helpers.test_cleanup()      yield      init_config()      helpers.test_cleanup()      def test_gui_service_arguments_hierarchy():      # Test default configuration      gui = Gui()      gui.run(run_server=False)      service_config = gui._config.config      assert not service_config["allow_unsafe_werkzeug"]      assert service_config["async_mode"] == "gevent"      assert service_config["change_delay"] is None      assert service_config["chart_dark_template"] is None      assert service_config["dark_mode"]      assert service_config["dark_theme"] is None      assert not service_config["debug"]      assert not service_config["extended_status"]      assert service_config["favicon"] is None      assert not service_config["flask_log"]      assert service_config["host"] == "127.0.0.1"      assert service_config["light_theme"] is None      assert service_config["margin"] is None      assert service_config["ngrok_token"] == ""      assert service_config["notification_duration"] == 3000      assert service_config["propagate"]      assert service_config["run_browser"]      assert not service_config["run_in_thread"]      assert not service_config["run_server"]      assert not service_config["single_client"]      assert not service_config["system_notification"]      assert service_config["theme"] is None      assert service_config["time_zone"] is None      assert service_config["title"] is None      assert service_config["upload_folder"] is None      assert not service_config["use_arrow"]      assert not service_config["use_reloader"]      assert service_config["watermark"] == "Taipy inside"      assert service_config["webapp_path"] is None      assert service_config["port"] == 5000      gui.stop()        # Override default configuration by explicit defined arguments in Gui.run()      gui = Gui()      gui.run(run_server=False, watermark="", host="my_host", port=5001)      service_config = gui._config.config      assert service_config["watermark"] == ""      assert service_config["host"] == "my_host"      assert service_config["port"] == 5001      gui.stop()        # Override Gui.run() arguments by explicit defined arguments in Config.configure_gui()      Config.configure_gui(dark_mode=False, host="my_2nd_host", port=5002)      gui = Gui()      gui.run(run_server=False, watermark="", host="my_host", port=5001)      service_config = gui._config.config      assert not service_config["dark_mode"]      assert service_config["host"] == "my_2nd_host"      assert service_config["watermark"] == ""      assert service_config["port"] == 5002      gui.stop()        # Override Config.configure_gui() arguments by loading a TOML file with [gui] section      toml_config = NamedTemporaryFile(          content="""  [TAIPY]    [gui]  host = "my_3rd_host"  port = 5003  use_reloader = "true:bool"      """      )      Config.load(toml_config.filename)      gui = Gui()      gui.run(run_server=False, host="my_host", port=5001)      service_config = gui._config.config      assert service_config["host"] == "my_3rd_host"      assert service_config["port"] == 5003      assert service_config["use_reloader"]      gui.stop()        # Override TOML configuration file with CLI arguments      with patch("sys.argv", ["prog", "--host", "my_4th_host", "--port", "5004", "--no-reloader", "--debug"]):          gui = Gui()          gui.run(run_server=False, host="my_host", port=5001)          service_config = gui._config.config          assert service_config["host"] == "my_4th_host"          assert service_config["port"] == 5004          assert not service_config["use_reloader"]          assert service_config["debug"]          gui.stop()      def test_clean_config():      gui_config = Config.configure_gui(dark_mode=False)        assert Config.gui_config is gui_config        gui_config._clean()        # Check if the instance before and after _clean() is the same      assert Config.gui_config is gui_config        assert gui_config.dark_mode is None      assert gui_config.properties == {}


import inspect  import warnings    import pytest    from taipy.gui import Gui      def test_no_ignore_file(gui: Gui):      with warnings.catch_warnings(record=True):          gui._set_frame(inspect.currentframe())          gui.run(run_server=False)          client = gui._server.test_client()          response = client.get("/resource.txt")          assert (              response.status_code == 200          ), f"file resource.txt request status should be 200 but is {response.status_code}"


import inspect  import warnings    import pytest    from taipy.gui import Gui      def test_ignore_file_found(gui: Gui):      with warnings.catch_warnings(record=True):          gui._set_frame(inspect.currentframe())          gui.run(run_server=False)          client = gui._server.test_client()          response = client.get("/resource.txt")          assert (              response.status_code == 404          ), f"file resource.txt request status should be 404 but is {response.status_code}"      def test_ignore_file_not_found(gui: Gui):      with warnings.catch_warnings(record=True):          gui._set_frame(inspect.currentframe())          gui.run(run_server=False)          client = gui._server.test_client()          response = client.get("/resource2.txt")          assert (              response.status_code == 200          ), f"file resource2.txt request status should be 200 but is {response.status_code}"


import inspect  import time  from urllib.request import urlopen    from taipy.gui import Gui      # this hangs in github  def test_run_thread(gui: Gui, helpers):      gui._set_frame(inspect.currentframe())      gui.add_page("page1", "# first page")      gui.run(run_in_thread=True, run_browser=False)      while not helpers.port_check():          time.sleep(0.1)      assert ">first page
" in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8")      gui.stop()      while helpers.port_check():          time.sleep(0.1)      gui.run(run_in_thread=True, run_browser=False)      while not helpers.port_check():          time.sleep(0.1)      assert ">first page
" in urlopen("http://127.0.0.1:5000/taipy-jsx/page1").read().decode("utf-8")


import pytest    from taipy.gui import Gui      def test_add_shared_variables(gui: Gui):      Gui.add_shared_variable("var1", "var2")      assert isinstance(gui._Gui__shared_variables, list)      assert len(gui._Gui__shared_variables) == 2        Gui.add_shared_variables("var1", "var2")      assert len(gui._Gui__shared_variables) == 2


import json    from taipy.gui.gui import Gui      def test_multiple_instance():      gui1 = Gui("<|gui1|>")      gui2 = Gui("<|gui2|>")      gui1.run(run_server=False)      gui2.run(run_server=False)      client1 = gui1._server.test_client()      client2 = gui2._server.test_client()      assert_multiple_instance(client1, 'value="gui1"')      assert_multiple_instance(client2, 'value="gui2"')      def assert_multiple_instance(client, expected_value):      response = client.get("/taipy-jsx/TaiPy_root_page")      response_data = json.loads(response.get_data().decode("utf-8", "ignore"))      assert response.status_code == 200      assert isinstance(response_data, dict)      assert "jsx" in response_data      assert expected_value in response_data["jsx"]


from taipy.gui.utils._variable_directory import _MODULE_NAME_MAP, _variable_decode, _variable_encode      def test_variable_encode_decode():      assert _variable_encode("x", "module") == "x_TPMDL_0"      assert _MODULE_NAME_MAP[0] == "module"      assert _variable_decode("x_TPMDL_0") == ("x", "module")      assert _variable_encode("x", None) == "x"      assert _variable_decode("x") == ("x", None)      assert _variable_encode("TpExPr_x", "module1") == "TpExPr_x_TPMDL_1"      assert _MODULE_NAME_MAP[1] == "module1"      assert _variable_decode("TpExPr_x_TPMDL_1") == ("x", "module1")


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="{"Letters": {"index": 0, "type": "object", "dfid": "Letters"}, "Numbers": {"index": 1, "type": "int", "dfid": "Numbers"}}"',          '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="[["1", "scenario 1"], ["3", "scenario 3"], ["2", "scenario 2"]]"',          'defaultValue="["1"]"',          '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


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
" 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
" 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
" 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")