test_on_change.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright 2023 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. import pytest
  14. from taipy.gui import Gui, Markdown
  15. def test_default_on_change(gui: Gui, helpers):
  16. st = {"d": False}
  17. def on_change(state, var, value):
  18. st["d"] = True
  19. x = 10 # noqa: F841
  20. # set gui frame
  21. gui._set_frame(inspect.currentframe())
  22. gui.add_page("test", Markdown("<|{x}|input|>"))
  23. with patch("sys.argv", ["prog"]):
  24. gui.run(run_server=False)
  25. flask_client = gui._server.test_client()
  26. # WS client and emit
  27. ws_client = gui._server._ws.test_client(gui._server.get_flask())
  28. # Get the jsx once so that the page will be evaluated -> variable will be registered
  29. sid = helpers.create_scope_and_get_sid(gui)
  30. flask_client.get(f"/taipy-jsx/test?client_id={sid}")
  31. # fake var update
  32. ws_client.emit("message", {"client_id": sid, "type": "U", "name": "x", "payload": {"value": "20"}})
  33. assert ws_client.get_received()
  34. assert st["d"] is True
  35. def test_specific_on_change(gui: Gui, helpers):
  36. st = {"d": False, "s": False}
  37. def on_change(state, var, value):
  38. st["d"] = True
  39. def on_input_change(state, var, value):
  40. st["s"] = True
  41. x = 10 # noqa: F841
  42. # set gui frame
  43. gui._set_frame(inspect.currentframe())
  44. gui.add_page("test", Markdown("<|{x}|input|on_change=on_input_change|>"))
  45. with patch("sys.argv", ["prog"]):
  46. gui.run(run_server=False)
  47. flask_client = gui._server.test_client()
  48. # WS client and emit
  49. ws_client = gui._server._ws.test_client(gui._server.get_flask())
  50. # Get the jsx once so that the page will be evaluated -> variable will be registered
  51. sid = helpers.create_scope_and_get_sid(gui)
  52. flask_client.get(f"/taipy-jsx/test?client_id={sid}")
  53. # fake var update
  54. ws_client.emit(
  55. "message",
  56. {"client_id": sid, "type": "U", "name": "x", "payload": {"value": "20", "on_change": "on_input_change"}},
  57. )
  58. assert ws_client.get_received()
  59. assert st["s"] is True
  60. assert st["d"] is False