helpers.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 json
  12. import logging
  13. import socket
  14. import time
  15. import typing as t
  16. import warnings
  17. from unittest.mock import patch
  18. from taipy.gui import Gui, Html, Markdown
  19. from taipy.gui._renderers.builder import _Builder
  20. from taipy.gui._warnings import TaipyGuiWarning
  21. from taipy.gui.utils._variable_directory import _reset_name_map
  22. from taipy.gui.utils.expr_var_name import _reset_expr_var_name
  23. class Helpers:
  24. @staticmethod
  25. def test_cleanup():
  26. _Builder._reset_key()
  27. _reset_name_map()
  28. _reset_expr_var_name()
  29. @staticmethod
  30. def test_control_md(gui: Gui, md_string: str, expected_values: t.Union[str, t.List]):
  31. gui.add_page("test", Markdown(md_string, frame=None))
  32. Helpers._test_control(gui, expected_values)
  33. @staticmethod
  34. def test_control_html(gui: Gui, html_string: str, expected_values: t.Union[str, t.List]):
  35. gui.add_page("test", Html(html_string, frame=None))
  36. Helpers._test_control(gui, expected_values)
  37. @staticmethod
  38. def test_control_builder(gui: Gui, builder_page, expected_values: t.Union[str, t.List]):
  39. gui.add_page("test", builder_page)
  40. Helpers._test_control(gui, expected_values)
  41. @staticmethod
  42. def _test_control(gui: Gui, expected_values: t.Union[str, t.List]):
  43. with patch("sys.argv", ["prog"]):
  44. gui.run(run_server=False, single_client=True, stylekit=False)
  45. client = gui._server.test_client()
  46. response = client.get("/taipy-jsx/test")
  47. assert response.status_code == 200, f"response.status_code {response.status_code} != 200"
  48. response_data = json.loads(response.get_data().decode("utf-8", "ignore"))
  49. assert isinstance(response_data, t.Dict), "response_data is not Dict"
  50. assert "jsx" in response_data, "jsx not in response_data"
  51. jsx = response_data["jsx"]
  52. logging.getLogger().debug(jsx)
  53. if isinstance(expected_values, str):
  54. assert jsx == expected_values, f"{jsx} != {expected_values}"
  55. elif isinstance(expected_values, list):
  56. for expected_value in expected_values:
  57. assert expected_value in jsx, f"{expected_value} not in {jsx}"
  58. @staticmethod
  59. def assert_outward_ws_message(received_message, type, varname, value):
  60. assert isinstance(received_message, dict)
  61. assert "name" in received_message and received_message["name"] == "message"
  62. assert "args" in received_message
  63. args = received_message["args"]
  64. assert "type" in args and args["type"] == type
  65. assert "payload" in args
  66. payload = args["payload"][0]
  67. assert "name" in payload and varname in payload["name"]
  68. assert "payload" in payload and "value" in payload["payload"] and payload["payload"]["value"] == value
  69. logging.getLogger().debug(payload["payload"]["value"])
  70. @staticmethod
  71. def assert_outward_simple_ws_message(received_message, type, varname, value):
  72. assert isinstance(received_message, dict)
  73. assert "name" in received_message and received_message["name"] == "message"
  74. assert "args" in received_message
  75. args = received_message["args"]
  76. assert "type" in args and args["type"] == type
  77. assert "name" in args and args["name"] == varname
  78. assert "payload" in args
  79. payload = args["payload"]
  80. assert "value" in payload and payload["value"] == value
  81. logging.getLogger().debug(payload["value"])
  82. @staticmethod
  83. def assert_outward_ws_simple_message(received_message, aType, values):
  84. assert isinstance(received_message, dict)
  85. assert "name" in received_message and received_message["name"] == "message"
  86. assert "args" in received_message
  87. args = received_message["args"]
  88. assert "type" in args and args["type"] == aType
  89. for k, v in values.items():
  90. assert k in args and args[k] == v
  91. logging.getLogger().debug(f"{k}: {args[k]}")
  92. @staticmethod
  93. def assert_outward_ws_multiple_message(received_message, type, array_len: int):
  94. assert isinstance(received_message, dict)
  95. assert "name" in received_message and received_message["name"] == "message"
  96. assert "args" in received_message
  97. args = received_message["args"]
  98. assert "type" in args and args["type"] == type
  99. assert "payload" in args
  100. payload = args["payload"]
  101. assert isinstance(payload, list)
  102. assert len(payload) == array_len
  103. logging.getLogger().debug(payload)
  104. @staticmethod
  105. def create_scope_and_get_sid(gui: Gui) -> str:
  106. sid = "test"
  107. gui._bindings()._get_or_create_scope(sid)
  108. return sid
  109. @staticmethod
  110. def port_check():
  111. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  112. s.settimeout(1)
  113. if s.connect_ex(("127.0.0.1", 5000)) == 0:
  114. s.close()
  115. return True
  116. else:
  117. s.close()
  118. return False
  119. @staticmethod
  120. def run_e2e(gui, **kwargs):
  121. kwargs["run_in_thread"] = True
  122. kwargs["single_client"] = True
  123. kwargs["run_browser"] = False
  124. kwargs["stylekit"] = kwargs.get("stylekit", False)
  125. with warnings.catch_warnings(record=True):
  126. with patch("sys.argv", ["prog"]):
  127. gui.run(**kwargs)
  128. while not Helpers.port_check():
  129. time.sleep(0.1)
  130. @staticmethod
  131. def run_e2e_multi_client(gui: Gui):
  132. with warnings.catch_warnings(record=True):
  133. with patch("sys.argv", ["prog"]):
  134. gui.run(run_server=False, run_browser=False, single_client=False, stylekit=False)
  135. gui._server.run(
  136. host=gui._get_config("host", "127.0.0.1"),
  137. port=gui._get_config("port", 5000),
  138. debug=False,
  139. use_reloader=False,
  140. flask_log=False,
  141. run_in_thread=True,
  142. allow_unsafe_werkzeug=False,
  143. notebook_proxy=False,
  144. )
  145. while not Helpers.port_check():
  146. time.sleep(0.1)
  147. @staticmethod
  148. def get_taipy_warnings(warns: t.List[warnings.WarningMessage]) -> t.List[warnings.WarningMessage]:
  149. return [w for w in warns if w.category is TaipyGuiWarning]