test_on_change.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import inspect
  12. from unittest.mock import patch
  13. from taipy.gui import Gui, Markdown
  14. def test_default_on_change(gui: Gui, helpers):
  15. st = {"d": False}
  16. def on_change(state, var, value):
  17. st["d"] = True
  18. x = 10 # noqa: F841
  19. # set gui frame
  20. gui._set_frame(inspect.currentframe())
  21. gui.add_page("test", Markdown("<|{x}|input|>"))
  22. with patch("sys.argv", ["prog"]):
  23. gui.run(run_server=False)
  24. flask_client = gui._server.test_client()
  25. # WS client and emit
  26. ws_client = gui._server._ws.test_client(gui._server.get_flask())
  27. # Get the jsx once so that the page will be evaluated -> variable will be registered
  28. sid = helpers.create_scope_and_get_sid(gui)
  29. flask_client.get(f"/taipy-jsx/test?client_id={sid}")
  30. # fake var update
  31. ws_client.emit("message", {"client_id": sid, "type": "U", "name": "x", "payload": {"value": "20"}})
  32. assert ws_client.get_received()
  33. assert st["d"] is True
  34. def test_specific_on_change(gui: Gui, helpers):
  35. st = {"d": False, "s": False}
  36. def on_change(state, var, value):
  37. st["d"] = True
  38. def on_input_change(state, var, value):
  39. st["s"] = True
  40. x = 10 # noqa: F841
  41. # set gui frame
  42. gui._set_frame(inspect.currentframe())
  43. gui.add_page("test", Markdown("<|{x}|input|on_change=on_input_change|>"))
  44. with patch("sys.argv", ["prog"]):
  45. gui.run(run_server=False)
  46. flask_client = gui._server.test_client()
  47. # WS client and emit
  48. ws_client = gui._server._ws.test_client(gui._server.get_flask())
  49. # Get the jsx once so that the page will be evaluated -> variable will be registered
  50. sid = helpers.create_scope_and_get_sid(gui)
  51. flask_client.get(f"/taipy-jsx/test?client_id={sid}")
  52. # fake var update
  53. ws_client.emit(
  54. "message",
  55. {"client_id": sid, "type": "U", "name": "x", "payload": {"value": "20", "on_change": "on_input_change"}},
  56. )
  57. assert ws_client.get_received()
  58. assert st["s"] is True
  59. assert st["d"] is False