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


import inspect  import logging  from importlib import util    import pytest    from taipy.gui import Gui    if util.find_spec("playwright"):      from playwright._impl._page import Page    from .assets.page1 import page as page1  from .assets.page2 import page as page2  from .assets.page3 import page as page3      @pytest.mark.timeout(300)  @pytest.mark.teste2e  def test_page_scopes(page: "Page", gui: Gui, helpers):      gui._set_frame(inspect.currentframe())        def on_change(state, var, val, module):          if var == "x" and "page3" in module:              state.y = val * 10        gui.add_page("page1", page1)      gui.add_page("page2", page2)      gui.add_page("page3", page3)      helpers.run_e2e(gui)        page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#x1")      assert page.query_selector("#x1").inner_text() == "10"      assert page.query_selector("#x2").inner_text() == "20"      assert page.query_selector("#y1").inner_text() == "20"      assert page.query_selector("#y2").inner_text() == "40"        page.goto("./page2")      page.expect_websocket()      page.wait_for_selector("#x1")      assert page.query_selector("#x1").inner_text() == "20"      assert page.query_selector("#x2").inner_text() == "40"      assert page.query_selector("#y1").inner_text() == "10"      assert page.query_selector("#y2").inner_text() == "20"        page.goto("./page3")      page.expect_websocket()      page.wait_for_selector("#x1")      assert page.query_selector("#x1").inner_text() == "50"      assert page.query_selector("#x2").inner_text() == "100"        page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#x1")      page.fill("#xinput", "15")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#y2').innerText !== '40'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      assert page.query_selector("#x1").inner_text() == "15"      assert page.query_selector("#x2").inner_text() == "30"      assert page.query_selector("#y1").inner_text() == "45"      assert page.query_selector("#y2").inner_text() == "90"        page.goto("./page2")      page.expect_websocket()      page.wait_for_selector("#x1")      assert page.query_selector("#x1").inner_text() == "45"      assert page.query_selector("#x2").inner_text() == "90"      assert page.query_selector("#y1").inner_text() == "15"      assert page.query_selector("#y2").inner_text() == "30"      page.fill("#xinput", "37")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#y2').innerText !== '30'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      assert page.query_selector("#x1").inner_text() == "37"      assert page.query_selector("#x2").inner_text() == "74"      assert page.query_selector("#y1").inner_text() == "185"      assert page.query_selector("#y2").inner_text() == "370"        page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#x1")      assert page.query_selector("#x1").inner_text() == "185"      assert page.query_selector("#x2").inner_text() == "370"      assert page.query_selector("#y1").inner_text() == "37"      assert page.query_selector("#y2").inner_text() == "74"        page.goto("./page3")      page.expect_websocket()      page.wait_for_selector("#x1")      assert page.query_selector("#x1").inner_text() == "50"      assert page.query_selector("#x2").inner_text() == "100"


import inspect  import logging  from importlib import util    import pytest    from taipy.gui import Gui, Markdown    if util.find_spec("playwright"):      from playwright._impl._page import Page    from .assets3.page1 import page as page1      def helpers_assert_text(page, s):      val1 = page.query_selector("#t1").inner_text()      assert str(val1).startswith(s)      # for issue #583  @pytest.mark.teste2e  @pytest.mark.filterwarnings("ignore::Warning")  def test_page_scopes_main_var_access(page: "Page", gui: Gui, helpers):      gui._set_frame(inspect.currentframe())      n = "Hello"  # noqa: F841        root_md = Markdown(          """    <|{n}|input|id=i1|>    """      )      gui.add_pages({"/": root_md, "page1": page1})      helpers.run_e2e(gui)        page.goto("./")      page.expect_websocket()      page.wait_for_selector("#t1")      page.wait_for_selector("#i1")      helpers_assert_text(page, "Hello")      page.fill("#i1", "Hello World")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#t1').innerText !== 'Hello'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      helpers_assert_text(page, "Hello World")


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


import inspect  import logging  from importlib import util    import pytest    from taipy.gui import Gui, Markdown    if util.find_spec("playwright"):      from playwright._impl._page import Page    from .assets3_class_scopes.page1 import Page1      def helpers_assert_text(page, s):      val1 = page.query_selector("#t1").inner_text()      assert str(val1).startswith(s)      # for issue #583  @pytest.mark.teste2e  @pytest.mark.filterwarnings("ignore::Warning")  def test_class_scopes_main_var_access(page: "Page", gui: Gui, helpers):      gui._set_frame(inspect.currentframe())      n = "Hello"  # noqa: F841        root_md = Markdown(          """    <|{n}|input|id=i1|>    """      )      gui.add_pages({"/": root_md, "page1": Page1()})      helpers.run_e2e(gui)        page.goto("./")      page.expect_websocket()      page.wait_for_selector("#t1")      page.wait_for_selector("#i1")      helpers_assert_text(page, "Hello")      page.fill("#i1", "Hello World")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#t1').innerText !== 'Hello'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      helpers_assert_text(page, "Hello World")


import inspect  import logging  from importlib import util    import pytest    from taipy.gui import Gui    if util.find_spec("playwright"):      from playwright._impl._page import Page    from .assets4.page1 import page as page1  from .assets4.page1 import reset_d      @pytest.mark.timeout(300)  @pytest.mark.teste2e  @pytest.mark.filterwarnings("ignore::Warning")  def test_page_scopes_state_runtime(page: "Page", gui: Gui, helpers):      gui._set_frame(inspect.currentframe())        def test(state):          reset_d(state)        def test2(state):          state["page1"].d = 30        page_md = """  <|button|on_action=test|id=btn1|>    <|button|on_action=test2|id=btn2|>  """      gui.add_page("page1", page1)      gui.add_page(name=Gui._get_root_page_name(), page=page_md)      helpers.run_e2e(gui)        page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#n1")      text1 = page.query_selector("#t1")      assert text1.inner_text() == "20"      page.fill("#n1", "21")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#t1').innerText !== '20'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      text1 = page.query_selector("#t1")      assert text1.inner_text() == "21"        page.click("#btn1")      try:          page.wait_for_function("document.querySelector('#t1').innerText !== '21'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      text1 = page.query_selector("#t1")      assert text1.inner_text() == "20"        page.click("#btn2")      try:          page.wait_for_function("document.querySelector('#t1').innerText !== '20'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      text1 = page.query_selector("#t1")      assert text1.inner_text() == "30"


import inspect  import logging  from importlib import util    import pytest    from taipy.gui import Gui    if util.find_spec("playwright"):      from playwright._impl._page import Page    from .assets2.page1 import page as page1  from .assets2.page2 import page as page2      def helpers_assert_value(page, s1, s2, v1):      s1_val = page.input_value("#s1 input")      assert str(s1_val).startswith(s1)      s2_val = page.input_value("#s2 input")      assert str(s2_val).startswith(s2)      val1 = page.query_selector("#v1").inner_text()      assert str(val1).startswith(v1)      @pytest.mark.timeout(300)  @pytest.mark.teste2e  @pytest.mark.filterwarnings("ignore::Warning")  def test_page_scopes_binding(page: "Page", gui: Gui, helpers):      gui._set_frame(inspect.currentframe())      operand_1 = 0  # noqa: F841      gui.add_page("page1", page1)      gui.add_page("page2", page2)      helpers.run_e2e(gui)        page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#s1")      helpers_assert_value(page, "0", "0", "0")      page.fill("#s1 input", "15")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#v1').innerText !== '0'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      helpers_assert_value(page, "15", "0", "15")      page.fill("#s2 input", "20")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#v1').innerText !== '15'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      helpers_assert_value(page, "15", "20", "35")        page.goto("./page2")      page.expect_websocket()      page.wait_for_selector("#s1")      helpers_assert_value(page, "15", "0", "0")      page.fill("#s2 input", "5")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#v1').innerText !== '0'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      helpers_assert_value(page, "15", "5", "75")      page.fill("#s1 input", "17")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#v1').innerText !== '75'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      helpers_assert_value(page, "17", "5", "85")        page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#s1")      helpers_assert_value(page, "17", "20", "37")


from taipy.gui import Markdown, Page      class Page1(Page):      def __init__(self):          self.operand_2 = 0          super().__init__()        def create_page(self):          return Markdown("page1.md")        def reset(state):          state.operand_2 = 0


from taipy.gui import Markdown, Page      class Page2(Page):      def __init__(self):          self.operand_2 = 0          super().__init__()        def create_page(self):          return Markdown("page2.md")


from taipy.gui import Markdown, Page      class Page1(Page):      def create_page(self):          return Markdown(              """    <|{n}|id=t1|>    """          )


from taipy.gui import Markdown    x = 10    y = 20      def on_change(state, var, val):      if var == "x":          state.y = val * 3      page = Markdown(      """  x = <|{x}|id=x1|>    x * 2 = <|{x*2}|id=x2|>    x number: <|{x}|number|id=xinput|>    y = <|{y}|id=y1|>    y * 2 = <|{y*2}|id=y2|>  """  )


from taipy.gui import Markdown    from .page1 import x as y  from .page1 import y as x      def on_change(state, var, val):      if var == "x":          state.y = val * 5      page = Markdown(      """  y = <|{x}|id=x1|>    y * 2 = <|{x*2}|id=x2|>    y number: <|{x}|number|id=xinput|>    x = <|{y}|id=y1|>    x * 2 = <|{y*2}|id=y2|>  """  )


from taipy.gui import Markdown    x = 50    page = Markdown(      """  <|{x}|id=x1|>    x * 2 = <|{x*2}|id=x2|>    <|{x}|number|id=xinput|>  """  )


from taipy.gui import Markdown    page = Markdown(      """    # Page1 - Add    Operand 1: <|{operand_1}|slider|id=s1|>    Operand 2: <|{operand_2}|slider|id=s2|>    Operand 1 + Operand 2 = <|{operand_1 + operand_2}|id=v1|>  """  )    operand_2 = 0


from taipy.gui import Markdown    page = Markdown(      """    # Page2 - Multiply    Operand 1: <|{operand_1}|slider|id=s1|>    Operand 2: <|{operand_2}|slider|id=s2|>    Operand 1 * Operand 2 = <|{operand_1 * operand_2}|id=v1|>  """  )    operand_2 = 0


from taipy.gui import Markdown    d = 20      def reset_d(state):      state.d = d  # a      page = Markdown(      """    <|{d}|text|id=t1|>    <|{d}|number|id=n1|>    """  )


from taipy.gui import Markdown    page = Markdown(      """    <|{n}|id=t1|>    """  )


import inspect  import logging  from importlib import util    import pytest    if util.find_spec("playwright"):      from playwright._impl._page import Page    from taipy.gui import Gui      @pytest.mark.teste2e  def test_slider_action(page: "Page", gui: Gui, helpers):      page_md = """  <|{x}|id=text1|>    <|{x}|slider|id=slider1|>  """      x = 10  # noqa: F841      gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("#text1")      text1 = page.query_selector("#text1")      assert text1.inner_text() == "10"      page.wait_for_selector("#slider1")      page.fill("#slider1 input", "20")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#text1').innerText !== '10'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          text1_2 = page.query_selector("#text1")          assert text1_2.inner_text() == "20"      @pytest.mark.teste2e  def test_slider_action_on_change(page: "Page", gui: Gui, helpers):      d = {"v1": 10, "v2": 10}  # noqa: F841        def on_change(state, var, val):          if var == "d.v2":              d = {"v1": 2 * val}              state.d.update(d)        page_md = """  Value: <|{d.v1}|id=text1|>    Slider: <|{d.v2}|slider|id=slider1|>  """      gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("#text1")      text1 = page.query_selector("#text1")      assert text1.inner_text() == "10"      page.wait_for_selector("#slider1")      page.fill("#slider1 input", "20")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#text1').innerText !== '10'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          text1_2 = page.query_selector("#text1")          assert text1_2.inner_text() == "40"


import inspect  import logging  from importlib import util    import pytest    if util.find_spec("playwright"):      from playwright._impl._page import Page    from taipy.gui import Gui      @pytest.mark.teste2e  def test_button_action(page: "Page", gui: Gui, helpers):      page_md = """  <|{x}|id=text1|>    <|Action|button|on_action=do_something_fn|id=button1|>  """      x = 10  # noqa: F841        def do_something_fn(state):          state.x = state.x * 2        gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("#text1")      text1 = page.query_selector("#text1")      assert text1.inner_text() == "10"      page.click("#button1")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#text1').innerText !== '10'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          text1_2 = page.query_selector("#text1")          assert text1_2.inner_text() == "20"


import inspect  import time  from importlib import util    import pytest    if util.find_spec("playwright"):      from playwright._impl._page import Page    from taipy.gui import Gui, State      @pytest.mark.teste2e  def test_selector_action(page: "Page", gui: Gui, helpers):      page_md = """  <|{x}|selector|lov=Item 1;Item 2;Item 3|id=selector1|>  """      x = "Item 1"  # noqa: F841        def on_init(state: State):          assert state.x == "Item 1"        def on_change(state: State, var, val):          if var == "x":              assert val == "Item 3"        gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("ul#selector1")      page.click('#selector1 > div[data-id="Item 3"]')      page.wait_for_function(          "document.querySelector('#selector1 > div[data-id=\"Item 3\"]').classList.contains('Mui-selected')"      )


import inspect  import logging  from importlib import util    import pytest    if util.find_spec("playwright"):      from playwright._impl._page import Page    from taipy.gui import Gui      def edit_and_assert_page(page: "Page"):      assert_input(page, "0")        page.fill("#input2 input", "20")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#val1').innerText !== '0'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      assert_input(page, "20")        page.fill("#input1", "30")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#val1').innerText !== '20'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if not function_evaluated:          return      assert_input(page, "30")      def assert_input(page: "Page", val: str):      val1 = page.query_selector("#val1").inner_text()      assert str(val1).startswith(val)      val2 = page.query_selector("#val2").inner_text()      assert str(val2).startswith(f"Val: {val}")      inp1 = page.input_value("input#input1")      assert str(inp1).startswith(val)      inp2 = page.input_value("#input2 input")      assert str(inp2).startswith(val)      @pytest.mark.filterwarnings("ignore::Warning")  @pytest.mark.teste2e  def test_slider_input_reload(page: "Page", gui: Gui, helpers):      page_md = """  #Test Multi Number    <|{val}|id=val1|>    <|Val: {val}|id=val2|>    <|{val}|number|id=input1|>    <|{val}|slider|id=input2|>  """      val = 0  # noqa: F841      gui._set_frame(inspect.currentframe())      gui.add_page(name="page1", page=page_md)      helpers.run_e2e_multi_client(gui)      page.goto("./page1")      page.expect_websocket()      page.wait_for_selector("#val1")      edit_and_assert_page(page)        page.reload()      page.expect_websocket()      page.wait_for_selector("#val1")      assert_input(page, "30")        page.evaluate("window.localStorage.removeItem('TaipyClientId')")        page.reload()      page.expect_websocket()      page.wait_for_selector("#val1")      assert_input(page, "0")


import inspect  import logging  from importlib import util    import pytest    if util.find_spec("playwright"):      from playwright._impl._page import Page    from taipy.gui import Gui      @pytest.mark.teste2e  def test_dict(page: "Page", gui: Gui, helpers):      page_md = """  <|{a_dict[a_key]}|input|id=inp1|>  <|{a_dict.key}|input|id=inp2|>  <|test|button|on_action=on_action_1|id=btn1|>  <|test|button|on_action=on_action_2|id=btn2|>  """      a_key = "key"      a_dict = {a_key: "Taipy"}  # noqa: F841        def on_action_1(state):          state.a_dict.key = "Hello"        def on_action_2(state):          state.a_dict[state.a_key] = "World"        gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("#inp1")        assert_text(page, "Taipy", "Taipy")        page.fill("input#inp1", "Taipy is the best")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#inp2').value !== 'Taipy'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          assert_text(page, "Taipy is the best", "Taipy is the best")        page.fill("#inp2", "Taipy-Gui")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#inp1').value !== 'Taipy is the best'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          assert_text(page, "Taipy-Gui", "Taipy-Gui")        page.click("#btn1")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#inp1').value !== 'Taipy-Gui'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          assert_text(page, "Hello", "Hello")        page.click("#btn2")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#inp1').value !== 'Hello'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          assert_text(page, "World", "World")      def assert_text(page, inp1, inp2):      assert page.input_value("input#inp1") == inp1      assert page.input_value("input#inp2") == inp2


import inspect  import logging  from importlib import util    import pytest    if util.find_spec("playwright"):      from playwright._impl._page import Page    from taipy.gui import Gui      @pytest.mark.teste2e  def test_text_edit(page: "Page", gui: Gui, helpers):      page_md = """  <|{x}|text|id=text1|>    <|{x}|input|id=input1|>  """      x = "Hey"  # noqa: F841      gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("#text1")      text1 = page.query_selector("#text1")      assert text1.inner_text() == "Hey"      page.wait_for_selector("#input1")      page.fill("#input1", "There")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#text1').innerText !== 'Hey'")      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          text1_2 = page.query_selector("#text1")          assert text1_2.inner_text() == "There"      @pytest.mark.teste2e  def test_number_edit(page: "Page", gui: Gui, helpers):      page_md = """  <|{x}|text|id=text1|>    <|{x}|number|id=number1|>    """      x = 10  # noqa: F841      gui._set_frame(inspect.currentframe())      gui.add_page(name="test", page=page_md)      helpers.run_e2e(gui)      page.goto("./test")      page.expect_websocket()      page.wait_for_selector("#text1")      text1 = page.query_selector("#text1")      assert text1.inner_text() == "10"      page.wait_for_selector("#number1")      page.fill("#number1", "20")      function_evaluated = True      try:          page.wait_for_function("document.querySelector('#text1').innerText !== '10'")          function_evaluated = True      except Exception as e:          function_evaluated = False          logging.getLogger().debug(f"Function evaluation timeout.\n{e}")      if function_evaluated:          text1_2 = page.query_selector("#text1")          assert text1_2.inner_text() == "20"