from unittest import mock    import pytest    from src.taipy.core._orchestrator._dispatcher import _DevelopmentJobDispatcher, _JobDispatcher, _StandaloneJobDispatcher  from src.taipy.core._orchestrator._orchestrator import _Orchestrator  from src.taipy.core._orchestrator._orchestrator_factory import _OrchestratorFactory  from src.taipy.core.config.job_config import JobConfig  from src.taipy.core.exceptions.exceptions import OrchestratorNotBuilt  from taipy.config import Config      def test_build_orchestrator():      _OrchestratorFactory._orchestrator = None      _OrchestratorFactory._dispatcher = None        assert _OrchestratorFactory._orchestrator is None      assert _OrchestratorFactory._dispatcher is None        orchestrator = _OrchestratorFactory._build_orchestrator()      assert orchestrator == _Orchestrator      assert _OrchestratorFactory._orchestrator == _Orchestrator      dispatcher = _OrchestratorFactory._build_dispatcher()      assert isinstance(dispatcher, _JobDispatcher)      assert isinstance(_OrchestratorFactory._dispatcher, _JobDispatcher)        _OrchestratorFactory._orchestrator = None      assert _OrchestratorFactory._orchestrator is None      assert _OrchestratorFactory._dispatcher is not None        with mock.patch(          "src.taipy.core._orchestrator._orchestrator_factory._OrchestratorFactory._build_dispatcher"      ) as build_dispatcher, mock.patch(          "src.taipy.core._orchestrator._orchestrator._Orchestrator.initialize"      ) as initialize:          orchestrator = _OrchestratorFactory._build_orchestrator()          assert orchestrator == _Orchestrator          assert _OrchestratorFactory._orchestrator == _Orchestrator          build_dispatcher.assert_not_called()          initialize.assert_called_once()      def test_build_development_dispatcher():      Config.configure_job_executions(mode=JobConfig._DEVELOPMENT_MODE)      _OrchestratorFactory._orchestrator = None      _OrchestratorFactory._dispatcher = None        assert _OrchestratorFactory._orchestrator is None      assert _OrchestratorFactory._dispatcher is None        with pytest.raises(OrchestratorNotBuilt):          _OrchestratorFactory._build_dispatcher()        _OrchestratorFactory._build_orchestrator()      assert _OrchestratorFactory._orchestrator is not None      assert _OrchestratorFactory._dispatcher is None        _OrchestratorFactory._build_dispatcher()      assert isinstance(_OrchestratorFactory._dispatcher, _DevelopmentJobDispatcher)      def test_build_standalone_dispatcher():      Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2)      _OrchestratorFactory._build_dispatcher()      assert isinstance(_OrchestratorFactory._dispatcher, _StandaloneJobDispatcher)      assert not isinstance(_OrchestratorFactory._dispatcher, _DevelopmentJobDispatcher)      assert _OrchestratorFactory._dispatcher.is_running()      assert _OrchestratorFactory._dispatcher._nb_available_workers == 2      _OrchestratorFactory._dispatcher._nb_available_workers = 1        _OrchestratorFactory._build_dispatcher(force_restart=False)      assert _OrchestratorFactory._dispatcher.is_running()      assert _OrchestratorFactory._dispatcher._nb_available_workers == 1        _OrchestratorFactory._build_dispatcher(force_restart=True)      assert _OrchestratorFactory._dispatcher.is_running()      assert _OrchestratorFactory._dispatcher._nb_available_workers == 2


import multiprocessing  from concurrent.futures import ProcessPoolExecutor  from functools import partial  from unittest import mock  from unittest.mock import MagicMock    from pytest import raises    from src.taipy.core import DataNodeId, JobId, TaskId  from src.taipy.core._orchestrator._dispatcher._development_job_dispatcher import _DevelopmentJobDispatcher  from src.taipy.core._orchestrator._dispatcher._standalone_job_dispatcher import _StandaloneJobDispatcher  from src.taipy.core._orchestrator._orchestrator_factory import _OrchestratorFactory  from src.taipy.core.config.job_config import JobConfig  from src.taipy.core.data._data_manager import _DataManager  from src.taipy.core.job.job import Job  from src.taipy.core.submission._submission_manager_factory import _SubmissionManagerFactory  from src.taipy.core.task.task import Task  from taipy.config.config import Config  from tests.core.utils import assert_true_after_time      def execute(lock):      with lock:          ...      return None      def _error():      raise RuntimeError("Something bad has happened")      def test_build_development_job_dispatcher():      Config.configure_job_executions(mode=JobConfig._DEVELOPMENT_MODE)      _OrchestratorFactory._build_dispatcher()      dispatcher = _OrchestratorFactory._dispatcher        assert isinstance(dispatcher, _DevelopmentJobDispatcher)      assert dispatcher._nb_available_workers == 1        with raises(NotImplementedError):          assert dispatcher.start()        assert dispatcher.is_running()        with raises(NotImplementedError):          dispatcher.stop()      def test_build_standalone_job_dispatcher():      Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2)      _OrchestratorFactory._build_dispatcher()      dispatcher = _OrchestratorFactory._dispatcher        assert not isinstance(dispatcher, _DevelopmentJobDispatcher)      assert isinstance(dispatcher, _StandaloneJobDispatcher)      assert isinstance(dispatcher._executor, ProcessPoolExecutor)      assert dispatcher._nb_available_workers == 2      assert_true_after_time(dispatcher.is_running)      dispatcher.stop()      dispatcher.join()      assert_true_after_time(lambda: not dispatcher.is_running())      def test_can_execute_2_workers():      Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2)        m = multiprocessing.Manager()      lock = m.Lock()        task_id = TaskId("task_id1")      output = list(_DataManager._bulk_get_or_create([Config.configure_data_node("input1", default_data=21)]).values())        _OrchestratorFactory._build_dispatcher()        task = Task(          config_id="name",          properties={},          input=[],          function=partial(execute, lock),          output=output,          id=task_id,      )      job_id = JobId("id1")      job = Job(job_id, task, "submit_id", task.id)        dispatcher = _StandaloneJobDispatcher(_OrchestratorFactory._orchestrator)        with lock:          assert dispatcher._can_execute()          dispatcher._dispatch(job)          assert dispatcher._can_execute()          dispatcher._dispatch(job)          assert not dispatcher._can_execute()        assert_true_after_time(lambda: dispatcher._can_execute())      def test_can_execute_synchronous():      Config.configure_job_executions(mode=JobConfig._DEVELOPMENT_MODE)      _OrchestratorFactory._build_dispatcher()        task_id = TaskId("task_id1")      task = Task(config_id="name", properties={}, input=[], function=print, output=[], id=task_id)      submission = _SubmissionManagerFactory._build_manager()._create(task_id, task._ID_PREFIX)      job_id = JobId("id1")      job = Job(job_id, task, submission.id, task.id)        dispatcher = _OrchestratorFactory._dispatcher        assert dispatcher._can_execute()      dispatcher._dispatch(job)      assert dispatcher._can_execute()      def test_exception_in_user_function():      Config.configure_job_executions(mode=JobConfig._DEVELOPMENT_MODE)      _OrchestratorFactory._build_dispatcher()        task_id = TaskId("task_id1")      job_id = JobId("id1")      task = Task(config_id="name", properties={}, input=[], function=_error, output=[], id=task_id)      submission = _SubmissionManagerFactory._build_manager()._create(task_id, task._ID_PREFIX)      job = Job(job_id, task, submission.id, task.id)        dispatcher = _OrchestratorFactory._dispatcher      dispatcher._dispatch(job)      assert job.is_failed()      assert 'RuntimeError("Something bad has happened")' in str(job.stacktrace[0])      def test_exception_in_writing_data():      Config.configure_job_executions(mode=JobConfig._DEVELOPMENT_MODE)      _OrchestratorFactory._build_dispatcher()        task_id = TaskId("task_id1")      job_id = JobId("id1")      output = MagicMock()      output.id = DataNodeId("output_id")      output.config_id = "my_raising_datanode"      output._is_in_cache = False      output.write.side_effect = ValueError()      task = Task(config_id="name", properties={}, input=[], function=print, output=[output], id=task_id)      submission = _SubmissionManagerFactory._build_manager()._create(task_id, task._ID_PREFIX)      job = Job(job_id, task, submission.id, task.id)        dispatcher = _OrchestratorFactory._dispatcher        with mock.patch("src.taipy.core.data._data_manager._DataManager._get") as get:          get.return_value = output          dispatcher._dispatch(job)          assert job.is_failed()          assert "node" in job.stacktrace[0]


#  # 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.


from src.taipy.core.data import InMemoryDataNode  from src.taipy.core.data._data_manager_factory import _DataManagerFactory  from src.taipy.core.task._task_model import _TaskModel  from taipy.config.common.scope import Scope      def test_none_properties_attribute_compatible():      model = _TaskModel.from_dict(          {              "id": "id",              "config_id": "config_id",              "parent_id": "owner_id",              "parent_ids": ["parent_id"],              "input_ids": ["input_id"],              "function_name": "function_name",              "function_module": "function_module",              "output_ids": ["output_id"],              "version": "latest",              "skippable": False,          }      )      assert len(model.properties) == 0      def test_skippable_compatibility_with_non_existing_output():      model = _TaskModel.from_dict(          {              "id": "id",              "config_id": "config_id",              "owner_id": "owner_id",              "parent_ids": ["parent_id"],              "input_ids": ["input_id"],              "function_name": "function_name",              "function_module": "function_module",              "output_ids": ["output_id"],              "version": "latest",              "skippable": False,          }      )      assert not model.skippable      def test_skippable_compatibility_with_no_output():      model = _TaskModel.from_dict(          {              "id": "id",              "config_id": "config_id",              "owner_id": "owner_id",              "parent_ids": ["parent_id"],              "input_ids": ["input_id"],              "function_name": "function_name",              "function_module": "function_module",              "output_ids": [],              "version": "latest",              "skippable": False,          }      )      assert not model.skippable      def test_skippable_compatibility_with_one_output():      manager = _DataManagerFactory._build_manager()      manager._set(InMemoryDataNode("cfg_id", Scope.SCENARIO, id="dn_id"))        model = _TaskModel.from_dict(          {              "id": "id",              "config_id": "config_id",              "owner_id": "owner_id",              "parent_ids": ["parent_id"],              "input_ids": ["input_id"],              "function_name": "function_name",              "function_module": "function_module",              "output_ids": ["dn_id"],              "version": "latest",              "skippable": True,          }      )      assert model.skippable      def test_skippable_compatibility_with_many_outputs():      manager = _DataManagerFactory._build_manager()      manager._set(InMemoryDataNode("cfg_id", Scope.SCENARIO, id="dn_id"))      manager._set(InMemoryDataNode("cfg_id_2", Scope.SCENARIO, id="dn_2_id"))      model = _TaskModel.from_dict(          {              "id": "id",              "config_id": "config_id",              "owner_id": "owner_id",              "parent_ids": ["parent_id"],              "input_ids": ["input_id"],              "function_name": "function_name",              "function_module": "function_module",              "output_ids": ["dn_id", "dn_2_id"],              "version": "latest",              "skippable": True,          }      )      assert model.skippable


from src.taipy.core.sequence._sequence_converter import _SequenceConverter  from src.taipy.core.sequence.sequence import Sequence  from src.taipy.core.task.task import Task      def test_entity_to_model(sequence):      sequence_model_1 = _SequenceConverter._entity_to_model(sequence)      expected_sequence_model_1 = {          "id": "sequence_id",          "owner_id": "owner_id",          "parent_ids": ["parent_id_1", "parent_id_2"],          "properties": {},          "tasks": [],          "subscribers": [],          "version": "random_version_number",      }      sequence_model_1["parent_ids"] = sorted(sequence_model_1["parent_ids"])      assert sequence_model_1 == expected_sequence_model_1        task_1 = Task("task_1", {}, print)      task_2 = Task("task_2", {}, print)      sequence_2 = Sequence(          {"name": "sequence_2"},          [task_1, task_2],          "SEQUENCE_sq_1_SCENARIO_sc",          "SCENARIO_sc",          ["SCENARIO_sc"],          [],          "random_version",      )      sequence_model_2 = _SequenceConverter._entity_to_model(sequence_2)      expected_sequence_model_2 = {          "id": "SEQUENCE_sq_1_SCENARIO_sc",          "owner_id": "SCENARIO_sc",          "parent_ids": ["SCENARIO_sc"],          "properties": {"name": "sequence_2"},          "tasks": [task_1.id, task_2.id],          "subscribers": [],          "version": "random_version",      }      assert sequence_model_2 == expected_sequence_model_2


from src.taipy.core.data.data_node import DataNode  from src.taipy.core.data.in_memory import InMemoryDataNode  from taipy.config.common.scope import Scope      class FakeDataNode(InMemoryDataNode):      read_has_been_called = 0      write_has_been_called = 0        def __init__(self, config_id, **kwargs):          scope = kwargs.pop("scope", Scope.SCENARIO)          super().__init__(config_id=config_id, scope=scope, **kwargs)        def _read(self, query=None):          self.read_has_been_called += 1        def _write(self, data):          self.write_has_been_called += 1        @classmethod      def storage_type(cls) -> str:          return "fake_inmemory"        write = DataNode.write  # Make sure that the writing behavior comes from DataNode      class FakeDataframeDataNode(DataNode):      COLUMN_NAME_1 = "a"      COLUMN_NAME_2 = "b"        def __init__(self, config_id, default_data_frame, **kwargs):          super().__init__(config_id, **kwargs)          self.data = default_data_frame        def _read(self):          return self.data        @classmethod      def storage_type(cls) -> str:          return "fake_df_dn"      class FakeNumpyarrayDataNode(DataNode):      def __init__(self, config_id, default_array, **kwargs):          super().__init__(config_id, **kwargs)          self.data = default_array        def _read(self):          return self.data        @classmethod      def storage_type(cls) -> str:          return "fake_np_dn"      class FakeListDataNode(DataNode):      class Row:          def __init__(self, value):              self.value = value        def __init__(self, config_id, **kwargs):          super().__init__(config_id, **kwargs)          self.data = [self.Row(i) for i in range(10)]        def _read(self):          return self.data        @classmethod      def storage_type(cls) -> str:          return "fake_list_dn"      class CustomClass:      def __init__(self, a, b):          self.a = a          self.b = b      class FakeCustomDataNode(DataNode):      def __init__(self, config_id, **kwargs):          super().__init__(config_id, **kwargs)          self.data = [CustomClass(i, i * 2) for i in range(10)]        def _read(self):          return self.data      class FakeMultiSheetExcelDataFrameDataNode(DataNode):      def __init__(self, config_id, default_data_frame, **kwargs):          super().__init__(config_id, **kwargs)          self.data = {              "Sheet1": default_data_frame,              "Sheet2": default_data_frame,          }        def _read(self):          return self.data      class FakeMultiSheetExcelCustomDataNode(DataNode):      def __init__(self, config_id, **kwargs):          super().__init__(config_id, **kwargs)          self.data = {              "Sheet1": [CustomClass(i, i * 2) for i in range(10)],              "Sheet2": [CustomClass(i, i * 2) for i in range(10)],          }        def _read(self):          return self.data


import os    import pytest    from src.taipy.core.data._data_fs_repository import _DataFSRepository  from src.taipy.core.data._data_sql_repository import _DataSQLRepository  from src.taipy.core.data.data_node import DataNode, DataNodeId  from src.taipy.core.exceptions import ModelNotFound      class TestDataNodeRepository:      @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_save_and_load(self, data_node, repo, init_sql_repo):          repository = repo()          repository._save(data_node)            obj = repository._load(data_node.id)          assert isinstance(obj, DataNode)        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_exists(self, data_node, repo, init_sql_repo):          repository = repo()          repository._save(data_node)            assert repository._exists(data_node.id)          assert not repository._exists("not-existed-data-node")        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_load_all(self, data_node, repo, init_sql_repo):          repository = repo()          for i in range(10):              data_node.id = DataNodeId(f"data_node-{i}")              repository._save(data_node)          data_nodes = repository._load_all()            assert len(data_nodes) == 10        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_load_all_with_filters(self, data_node, repo, init_sql_repo):          repository = repo()            for i in range(10):              data_node.id = DataNodeId(f"data_node-{i}")              data_node.owner_id = f"task-{i}"              repository._save(data_node)          objs = repository._load_all(filters=[{"owner_id": "task-2"}])            assert len(objs) == 1        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_delete(self, data_node, repo, init_sql_repo):          repository = repo()          repository._save(data_node)            repository._delete(data_node.id)            with pytest.raises(ModelNotFound):              repository._load(data_node.id)        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_delete_all(self, data_node, repo, init_sql_repo):          repository = repo()            for i in range(10):              data_node.id = DataNodeId(f"data_node-{i}")              repository._save(data_node)            assert len(repository._load_all()) == 10            repository._delete_all()            assert len(repository._load_all()) == 0        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_delete_many(self, data_node, repo, init_sql_repo):          repository = repo()            for i in range(10):              data_node.id = DataNodeId(f"data_node-{i}")              repository._save(data_node)            objs = repository._load_all()          assert len(objs) == 10          ids = [x.id for x in objs[:3]]          repository._delete_many(ids)            assert len(repository._load_all()) == 7        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_delete_by(self, data_node, repo, init_sql_repo):          repository = repo()            # Create 5 entities with version 1.0 and 5 entities with version 2.0          for i in range(10):              data_node.id = DataNodeId(f"data_node-{i}")              data_node._version = f"{(i+1) // 5}.0"              repository._save(data_node)            objs = repository._load_all()          assert len(objs) == 10          repository._delete_by("version", "1.0")            assert len(repository._load_all()) == 5        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_search(self, data_node, repo, init_sql_repo):          repository = repo()            for i in range(10):              data_node.id = DataNodeId(f"data_node-{i}")              data_node.owner_id = f"task-{i}"              repository._save(data_node)            assert len(repository._load_all()) == 10            objs = repository._search("owner_id", "task-2")          assert len(objs) == 1          assert isinstance(objs[0], DataNode)            objs = repository._search("owner_id", "task-2", filters=[{"version": "random_version_number"}])          assert len(objs) == 1          assert isinstance(objs[0], DataNode)            assert repository._search("owner_id", "task-2", filters=[{"version": "non_existed_version"}]) == []        @pytest.mark.parametrize("repo", [_DataFSRepository, _DataSQLRepository])      def test_export(self, tmpdir, data_node, repo, init_sql_repo):          repository = repo()          repository._save(data_node)            repository._export(data_node.id, tmpdir.strpath)          dir_path = repository.dir_path if repo == _DataFSRepository else os.path.join(tmpdir.strpath, "data_node")            assert os.path.exists(os.path.join(dir_path, f"{data_node.id}.json"))


import pytest    from src.taipy.core.data.data_node_id import DataNodeId  from src.taipy.core.data.in_memory import InMemoryDataNode  from src.taipy.core.exceptions.exceptions import NoData  from taipy.config.common.scope import Scope  from taipy.config.exceptions.exceptions import InvalidConfigurationId      class TestInMemoryDataNodeEntity:      def test_create(self):          dn = InMemoryDataNode(              "foobar_bazy",              Scope.SCENARIO,              DataNodeId("id_uio"),              "owner_id",              properties={"default_data": "In memory Data Node", "name": "my name"},          )          assert isinstance(dn, InMemoryDataNode)          assert dn.storage_type() == "in_memory"          assert dn.config_id == "foobar_bazy"          assert dn.scope == Scope.SCENARIO          assert dn.id == "id_uio"          assert dn.name == "my name"          assert dn.owner_id == "owner_id"          assert dn.last_edit_date is not None          assert dn.job_ids == []          assert dn.is_ready_for_reading          assert dn.read() == "In memory Data Node"            dn_2 = InMemoryDataNode("foo", Scope.SCENARIO)          assert dn_2.last_edit_date is None          assert not dn_2.is_ready_for_reading            with pytest.raises(InvalidConfigurationId):              InMemoryDataNode("foo bar", Scope.SCENARIO, DataNodeId("dn_id"))        def test_get_user_properties(self):          dn = InMemoryDataNode("foo", Scope.SCENARIO, properties={"default_data": 1, "foo": "bar"})          assert dn._get_user_properties() == {"foo": "bar"}        def test_read_and_write(self):          no_data_dn = InMemoryDataNode("foo", Scope.SCENARIO, DataNodeId("dn_id"))          with pytest.raises(NoData):              assert no_data_dn.read() is None              no_data_dn.read_or_raise()          in_mem_dn = InMemoryDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar"})          assert isinstance(in_mem_dn.read(), str)          assert in_mem_dn.read() == "bar"          in_mem_dn.properties["default_data"] = "baz"  # this modifies the default data value but not the data itself          assert in_mem_dn.read() == "bar"          in_mem_dn.write("qux")          assert in_mem_dn.read() == "qux"          in_mem_dn.write(1998)          assert isinstance(in_mem_dn.read(), int)          assert in_mem_dn.read() == 1998


from datetime import datetime  from time import sleep    from src.taipy.core._version._version_manager_factory import _VersionManagerFactory  from src.taipy.core.submission._submission_manager_factory import _SubmissionManagerFactory  from src.taipy.core.submission.submission import Submission  from src.taipy.core.submission.submission_status import SubmissionStatus  from src.taipy.core.task.task import Task      def test_create_submission(scenario):      submission_1 = _SubmissionManagerFactory._build_manager()._create(scenario.id, scenario._ID_PREFIX)        assert submission_1.id is not None      assert submission_1.entity_id == scenario.id      assert submission_1.jobs == []      assert isinstance(submission_1.creation_date, datetime)      assert submission_1._submission_status == SubmissionStatus.SUBMITTED      def test_get_submission():      submission_manager = _SubmissionManagerFactory._build_manager()        assert submission_manager._get("random_submission_id") is None        submission_1 = submission_manager._create("entity_id", "ENTITY_TYPE")      submission_2 = submission_manager._get(submission_1.id)        assert submission_1.id == submission_2.id      assert submission_1.entity_id == submission_2.entity_id == "entity_id"      assert submission_1.jobs == submission_2.jobs      assert submission_1.creation_date == submission_2.creation_date      assert submission_1.submission_status == submission_2.submission_status      def test_get_all_submission():      submission_manager = _SubmissionManagerFactory._build_manager()      version_manager = _VersionManagerFactory._build_manager()        submission_manager._set(Submission("entity_id", "submission_id", version=version_manager._get_latest_version()))      for version_name in ["abc", "xyz"]:          for i in range(10):              submission_manager._set(                  Submission("entity_id", f"submission_{version_name}_{i}", version=f"{version_name}")              )        assert len(submission_manager._get_all()) == 1        version_manager._set_experiment_version("xyz")      version_manager._set_experiment_version("abc")      assert len(submission_manager._get_all()) == 10      assert len(submission_manager._get_all("abc")) == 10      assert len(submission_manager._get_all("xyz")) == 10      def test_get_latest_submission():      task_1 = Task("task_config_1", {}, print, id="task_id_1")      task_2 = Task("task_config_2", {}, print, id="task_id_2")        submission_manager = _SubmissionManagerFactory._build_manager()      submission_1 = submission_manager._create(task_1.id, task_1._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_1      assert submission_manager._get_latest(task_2) is None        sleep(0.01)  # Comparison is based on time, precision on Windows is not enough important      submission_2 = submission_manager._create(task_2.id, task_2._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_1      assert submission_manager._get_latest(task_2) == submission_2        sleep(0.01)  # Comparison is based on time, precision on Windows is not enough important      submission_3 = submission_manager._create(task_1.id, task_1._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_3      assert submission_manager._get_latest(task_2) == submission_2        sleep(0.01)  # Comparison is based on time, precision on Windows is not enough important      submission_4 = submission_manager._create(task_2.id, task_2._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_3      assert submission_manager._get_latest(task_2) == submission_4      def test_delete_submission():      submission_manager = _SubmissionManagerFactory._build_manager()        submission = Submission("entity_id", "submission_id")      submission_manager._set(submission)        for i in range(10):          submission_manager._set(Submission("entity_id", f"submission_{i}"))        assert len(submission_manager._get_all()) == 11      assert isinstance(submission_manager._get(submission.id), Submission)        submission_manager._delete(submission.id)      assert len(submission_manager._get_all()) == 10      assert submission_manager._get(submission.id) is None        submission_manager._delete_all()      assert len(submission_manager._get_all()) == 0


from datetime import datetime  from time import sleep    from src.taipy.core import Task  from src.taipy.core._repository.db._sql_connection import _SQLConnection  from src.taipy.core._version._version_manager_factory import _VersionManagerFactory  from src.taipy.core.submission._submission_manager_factory import _SubmissionManagerFactory  from src.taipy.core.submission.submission import Submission  from src.taipy.core.submission.submission_status import SubmissionStatus      def init_managers():      _VersionManagerFactory._build_manager()._delete_all()      _SubmissionManagerFactory._build_manager()._delete_all()      def test_create_submission(scenario, init_sql_repo):      init_managers()        submission_1 = _SubmissionManagerFactory._build_manager()._create(scenario.id, scenario._ID_PREFIX)        assert submission_1.id is not None      assert submission_1.entity_id == scenario.id      assert submission_1.jobs == []      assert isinstance(submission_1.creation_date, datetime)      assert submission_1._submission_status == SubmissionStatus.SUBMITTED      def test_get_submission(init_sql_repo):      init_managers()        submission_manager = _SubmissionManagerFactory._build_manager()        submission_1 = submission_manager._create("entity_id", "ENTITY_TYPE")      submission_2 = submission_manager._get(submission_1.id)        assert submission_1.id == submission_2.id      assert submission_1.entity_id == submission_2.entity_id == "entity_id"      assert submission_1.jobs == submission_2.jobs      assert submission_1.creation_date == submission_2.creation_date      assert submission_1.submission_status == submission_2.submission_status      def test_get_all_submission(init_sql_repo):      init_managers()        submission_manager = _SubmissionManagerFactory._build_manager()      version_manager = _VersionManagerFactory._build_manager()        submission_manager._set(Submission("entity_id", "submission_id", version=version_manager._get_latest_version()))      for version_name in ["abc", "xyz"]:          for i in range(10):              submission_manager._set(                  Submission("entity_id", f"submission_{version_name}_{i}", version=f"{version_name}")              )      assert len(submission_manager._get_all()) == 1        version_manager._set_experiment_version("xyz")      version_manager._set_experiment_version("abc")      assert len(submission_manager._get_all()) == 10      assert len(submission_manager._get_all("abc")) == 10      assert len(submission_manager._get_all("xyz")) == 10      def test_get_latest_submission(init_sql_repo):      init_managers()        task_1 = Task("task_config_1", {}, print, id="task_id_1")      task_2 = Task("task_config_2", {}, print, id="task_id_2")        submission_manager = _SubmissionManagerFactory._build_manager()      submission_1 = submission_manager._create(task_1.id, task_1._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_1      assert submission_manager._get_latest(task_2) is None        sleep(0.01)  # Comparison is based on time, precision on Windows is not enough important      submission_2 = submission_manager._create(task_2.id, task_2._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_1      assert submission_manager._get_latest(task_2) == submission_2        sleep(0.01)  # Comparison is based on time, precision on Windows is not enough important      submission_3 = submission_manager._create(task_1.id, task_1._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_3      assert submission_manager._get_latest(task_2) == submission_2        sleep(0.01)  # Comparison is based on time, precision on Windows is not enough important      submission_4 = submission_manager._create(task_2.id, task_2._ID_PREFIX)      assert submission_manager._get_latest(task_1) == submission_3      assert submission_manager._get_latest(task_2) == submission_4      def test_delete_submission(init_sql_repo):      init_managers()        submission_manager = _SubmissionManagerFactory._build_manager()        submission = Submission("entity_id", "submission_id")      submission_manager._set(submission)        for i in range(10):          submission_manager._set(Submission("entity_id", f"submission_{i}"))        assert len(submission_manager._get_all()) == 11      assert isinstance(submission_manager._get(submission.id), Submission)        submission_manager._delete(submission.id)      assert len(submission_manager._get_all()) == 10      assert submission_manager._get(submission.id) is None        submission_manager._delete_all()      assert len(submission_manager._get_all()) == 0


import os  import pathlib  from unittest import TestCase, mock    from src.taipy.logger._taipy_logger import _TaipyLogger      class TestTaipyLogger(TestCase):      def test_taipy_logger(self):          _TaipyLogger._get_logger().info("baz")          _TaipyLogger._get_logger().debug("qux")        def test_taipy_logger_configured_by_file(self):          path = os.path.join(pathlib.Path(__file__).parent.resolve(), "logger.conf")          with mock.patch.dict(os.environ, {"TAIPY_LOGGER_CONFIG_PATH": path}):              _TaipyLogger._get_logger().info("baz")              _TaipyLogger._get_logger().debug("qux")


import os    import pytest    from src.taipy.config.config import Config  from src.taipy.config.exceptions.exceptions import ConfigurationUpdateBlocked  from tests.config.utils.named_temporary_file import NamedTemporaryFile    config_from_filename = NamedTemporaryFile(      """  [TAIPY]  custom_property_not_overwritten = true  custom_property_overwritten = 10  """  )    config_from_environment = NamedTemporaryFile(      """  [TAIPY]  custom_property_overwritten = 11  """  )      def test_load_from_environment_overwrite_load_from_filename():      os.environ[Config._ENVIRONMENT_VARIABLE_NAME_WITH_CONFIG_PATH] = config_from_environment.filename      Config.load(config_from_filename.filename)        assert Config.global_config.custom_property_not_overwritten is True      assert Config.global_config.custom_property_overwritten == 11      os.environ.pop(Config._ENVIRONMENT_VARIABLE_NAME_WITH_CONFIG_PATH)      def test_block_load_from_environment_overwrite_load_from_filename():      Config.load(config_from_filename.filename)      assert Config.global_config.custom_property_not_overwritten is True      assert Config.global_config.custom_property_overwritten == 10        Config.block_update()        with pytest.raises(ConfigurationUpdateBlocked):          os.environ[Config._ENVIRONMENT_VARIABLE_NAME_WITH_CONFIG_PATH] = config_from_environment.filename          Config.load(config_from_filename.filename)        os.environ.pop(Config._ENVIRONMENT_VARIABLE_NAME_WITH_CONFIG_PATH)      assert Config.global_config.custom_property_not_overwritten is True      assert Config.global_config.custom_property_overwritten == 10  # The Config.load is failed to override


import pytest    from src.taipy.config._config import _Config  from src.taipy.config._config_comparator._config_comparator import _ConfigComparator  from src.taipy.config._serializer._toml_serializer import _TomlSerializer  from src.taipy.config.checker.issue_collector import IssueCollector  from src.taipy.config.config import Config  from src.taipy.config.section import Section  from tests.config.utils.section_for_tests import SectionForTest  from tests.config.utils.unique_section_for_tests import UniqueSectionForTest      @pytest.fixture(scope="function", autouse=True)  def reset():      reset_configuration_singleton()      register_test_sections()      def reset_configuration_singleton():      Config.unblock_update()      Config._default_config = _Config()._default_config()      Config._python_config = _Config()      Config._file_config = _Config()      Config._env_file_config = _Config()      Config._applied_config = _Config()      Config._collector = IssueCollector()      Config._serializer = _TomlSerializer()      Config._comparator = _ConfigComparator()      def register_test_sections():      Config._register_default(UniqueSectionForTest("default_attribute"))      Config.configure_unique_section_for_tests = UniqueSectionForTest._configure      Config.unique_section_name = Config.unique_sections[UniqueSectionForTest.name]        Config._register_default(SectionForTest(Section._DEFAULT_KEY, "default_attribute", prop="default_prop", prop_int=0))      Config.configure_section_for_tests = SectionForTest._configure      Config.section_name = Config.sections[SectionForTest.name]


import os  from unittest import mock    import pytest    from src.taipy.config.exceptions.exceptions import InvalidConfigurationId  from tests.config.utils.section_for_tests import SectionForTest  from tests.config.utils.unique_section_for_tests import UniqueSectionForTest      class WrongUniqueSection(UniqueSectionForTest):      name = "1wrong_id"      class WrongSection(SectionForTest):      name = "correct_name"      def test_section_uses_valid_id():      with pytest.raises(InvalidConfigurationId):          WrongUniqueSection(attribute="foo")      with pytest.raises(InvalidConfigurationId):          WrongSection("wrong id", attribute="foo")      with pytest.raises(InvalidConfigurationId):          WrongSection("1wrong_id", attribute="foo")      with pytest.raises(InvalidConfigurationId):          WrongSection("wrong_@id", attribute="foo")      def test_templated_properties_are_replaced():      with mock.patch.dict(os.environ, {"foo": "bar", "baz": "1"}):          u_sect = UniqueSectionForTest(attribute="attribute", tpl_property="ENV[foo]")          assert u_sect.tpl_property == "bar"            sect = SectionForTest(id="my_id", attribute="attribute", tpl_property="ENV[baz]:int")          assert sect.tpl_property == 1


from src.taipy.config.config import Config  from src.taipy.config.global_app.global_app_config import GlobalAppConfig  from src.taipy.config.section import Section  from tests.config.utils.section_for_tests import SectionForTest  from tests.config.utils.unique_section_for_tests import UniqueSectionForTest      def _test_default_global_app_config(global_config: GlobalAppConfig):      assert global_config is not None      assert not global_config.notification      assert len(global_config.properties) == 0      def test_default_configuration():      default_config = Config._default_config      assert default_config._unique_sections is not None      assert len(default_config._unique_sections) == 1      assert default_config._unique_sections[UniqueSectionForTest.name] is not None      assert default_config._unique_sections[UniqueSectionForTest.name].attribute == "default_attribute"      assert default_config._sections is not None      assert len(default_config._sections) == 1        _test_default_global_app_config(default_config._global_config)      _test_default_global_app_config(Config.global_config)      _test_default_global_app_config(GlobalAppConfig().default_config())      def test_register_default_configuration():      Config._register_default(SectionForTest(Section._DEFAULT_KEY, "default_attribute", prop1="prop1"))        # Replace the first default section      Config._register_default(SectionForTest(Section._DEFAULT_KEY, "default_attribute", prop2="prop2"))        default_section = Config.sections[SectionForTest.name][Section._DEFAULT_KEY]      assert len(default_section.properties) == 1      assert default_section.prop2 == "prop2"      assert default_section.prop1 is None


import pytest    from src.taipy.config.config import Config  from src.taipy.config.exceptions.exceptions import LoadingError  from tests.config.utils.named_temporary_file import NamedTemporaryFile      def test_node_can_not_appear_twice():      config = NamedTemporaryFile(          """  [unique_section_name]  attribute = "my_attribute"    [unique_section_name]  attribute = "other_attribute"      """      )        with pytest.raises(LoadingError, match="Can not load configuration"):          Config.load(config.filename)      def test_skip_configuration_outside_nodes():      config = NamedTemporaryFile(          """  foo = "bar"      """      )        Config.load(config.filename)      assert Config.global_config.foo is None


from src.taipy.config._config import _Config  from src.taipy.config.checker._checker import _Checker      class TestDefaultConfigChecker:      def test_check_default_config(self):          config = _Config._default_config()          collector = _Checker._check(config)          assert len(collector._errors) == 0          assert len(collector._infos) == 0          assert len(collector._warnings) == 0


from src.taipy.config.checker.issue import Issue  from src.taipy.config.checker.issue_collector import IssueCollector      class TestIssueCollector:      def test_add_error(self):          collector = IssueCollector()          assert len(collector.errors) == 0          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert len(collector.all) == 0          collector._add_error("field", "value", "message", "checker")          assert len(collector.errors) == 1          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert len(collector.all) == 1          assert collector.all[0] == Issue(IssueCollector._ERROR_LEVEL, "field", "value", "message", "checker")          collector._add_error("field", "value", "message", "checker")          assert len(collector.errors) == 2          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert len(collector.all) == 2          assert collector.all[0] == Issue(IssueCollector._ERROR_LEVEL, "field", "value", "message", "checker")          assert collector.all[1] == Issue(IssueCollector._ERROR_LEVEL, "field", "value", "message", "checker")        def test_add_warning(self):          collector = IssueCollector()          assert len(collector.errors) == 0          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert len(collector.all) == 0          collector._add_warning("field", "value", "message", "checker")          assert len(collector.errors) == 0          assert len(collector.warnings) == 1          assert len(collector.infos) == 0          assert len(collector.all) == 1          assert collector.all[0] == Issue(IssueCollector._WARNING_LEVEL, "field", "value", "message", "checker")          collector._add_warning("field", "value", "message", "checker")          assert len(collector.errors) == 0          assert len(collector.warnings) == 2          assert len(collector.infos) == 0          assert len(collector.all) == 2          assert collector.all[0] == Issue(IssueCollector._WARNING_LEVEL, "field", "value", "message", "checker")          assert collector.all[1] == Issue(IssueCollector._WARNING_LEVEL, "field", "value", "message", "checker")        def test_add_info(self):          collector = IssueCollector()          assert len(collector.errors) == 0          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert len(collector.all) == 0          collector._add_info("field", "value", "message", "checker")          assert len(collector.errors) == 0          assert len(collector.warnings) == 0          assert len(collector.infos) == 1          assert len(collector.all) == 1          assert collector.all[0] == Issue(IssueCollector._INFO_LEVEL, "field", "value", "message", "checker")          collector._add_info("field", "value", "message", "checker")          assert len(collector.errors) == 0          assert len(collector.warnings) == 0          assert len(collector.infos) == 2          assert len(collector.all) == 2          assert collector.all[0] == Issue(IssueCollector._INFO_LEVEL, "field", "value", "message", "checker")          assert collector.all[1] == Issue(IssueCollector._INFO_LEVEL, "field", "value", "message", "checker")        def test_all(self):          collector = IssueCollector()          collector._add_info("foo", "bar", "baz", "qux")          assert collector.all[0] == Issue(IssueCollector._INFO_LEVEL, "foo", "bar", "baz", "qux")          collector._add_warning("foo2", "bar2", "baz2", "qux2")          assert collector.all[0] == Issue(IssueCollector._WARNING_LEVEL, "foo2", "bar2", "baz2", "qux2")          assert collector.all[1] == Issue(IssueCollector._INFO_LEVEL, "foo", "bar", "baz", "qux")          collector._add_warning("foo3", "bar3", "baz3", "qux3")          assert collector.all[0] == Issue(IssueCollector._WARNING_LEVEL, "foo2", "bar2", "baz2", "qux2")          assert collector.all[1] == Issue(IssueCollector._WARNING_LEVEL, "foo3", "bar3", "baz3", "qux3")          assert collector.all[2] == Issue(IssueCollector._INFO_LEVEL, "foo", "bar", "baz", "qux")          collector._add_info("field", "value", "message", "checker")          collector._add_error("field", "value", "message", "checker")          assert collector.all[0] == Issue(IssueCollector._ERROR_LEVEL, "field", "value", "message", "checker")          assert collector.all[1] == Issue(IssueCollector._WARNING_LEVEL, "foo2", "bar2", "baz2", "qux2")          assert collector.all[2] == Issue(IssueCollector._WARNING_LEVEL, "foo3", "bar3", "baz3", "qux3")          assert collector.all[3] == Issue(IssueCollector._INFO_LEVEL, "foo", "bar", "baz", "qux")          assert collector.all[4] == Issue(IssueCollector._INFO_LEVEL, "field", "value", "message", "checker")


import os  from unittest import mock  from unittest.mock import MagicMock    from src.taipy.config import Config  from src.taipy.config.checker._checker import _Checker  from src.taipy.config.checker.issue_collector import IssueCollector  from tests.config.utils.checker_for_tests import CheckerForTest      def test_register_checker():      checker = CheckerForTest      checker._check = MagicMock()      _Checker.add_checker(checker)      Config.check()      checker._check.assert_called_once()


import logging  from unittest import mock    from src.taipy.config._config import _Config  from src.taipy.config.checker._checkers._config_checker import _ConfigChecker  from src.taipy.config.checker.issue import Issue  from src.taipy.config.checker.issue_collector import IssueCollector      class MyCustomChecker(_ConfigChecker):      def _check(self) -> IssueCollector:  # type: ignore          pass      def test__error():      with mock.patch.object(logging.Logger, "error"):          collector = IssueCollector()          assert len(collector.all) == 0          _ConfigChecker(_Config(), collector)._error("field", 17, "my message")          assert len(collector.all) == 1          assert len(collector.errors) == 1          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert collector.errors[0] == Issue(IssueCollector._ERROR_LEVEL, "field", 17, "my message", "_ConfigChecker")            MyCustomChecker(_Config(), collector)._error("foo", "bar", "baz")          assert len(collector.all) == 2          assert len(collector.errors) == 2          assert len(collector.warnings) == 0          assert len(collector.infos) == 0          assert collector.errors[0] == Issue(IssueCollector._ERROR_LEVEL, "field", 17, "my message", "_ConfigChecker")          assert collector.errors[1] == Issue(IssueCollector._ERROR_LEVEL, "foo", "bar", "baz", "MyCustomChecker")      def test__warning():      collector = IssueCollector()      assert len(collector.all) == 0      _ConfigChecker(_Config(), collector)._warning("field", 17, "my message")      assert len(collector.all) == 1      assert len(collector.warnings) == 1      assert len(collector.errors) == 0      assert len(collector.infos) == 0      assert collector.warnings[0] == Issue(IssueCollector._WARNING_LEVEL, "field", 17, "my message", "_ConfigChecker")        MyCustomChecker(_Config(), collector)._warning("foo", "bar", "baz")      assert len(collector.all) == 2      assert len(collector.warnings) == 2      assert len(collector.errors) == 0      assert len(collector.infos) == 0      assert collector.warnings[0] == Issue(IssueCollector._WARNING_LEVEL, "field", 17, "my message", "_ConfigChecker")      assert collector.warnings[1] == Issue(IssueCollector._WARNING_LEVEL, "foo", "bar", "baz", "MyCustomChecker")      def test__info():      collector = IssueCollector()      assert len(collector.all) == 0      _ConfigChecker(_Config(), collector)._info("field", 17, "my message")      assert len(collector.all) == 1      assert len(collector.infos) == 1      assert len(collector.errors) == 0      assert len(collector.warnings) == 0      assert collector.infos[0] == Issue(IssueCollector._INFO_LEVEL, "field", 17, "my message", "_ConfigChecker")        MyCustomChecker(_Config(), collector)._info("foo", "bar", "baz")      assert len(collector.all) == 2      assert len(collector.infos) == 2      assert len(collector.errors) == 0      assert len(collector.warnings) == 0      assert collector.infos[0] == Issue(IssueCollector._INFO_LEVEL, "field", 17, "my message", "_ConfigChecker")      assert collector.infos[1] == Issue(IssueCollector._INFO_LEVEL, "foo", "bar", "baz", "MyCustomChecker")


from src.taipy.config import IssueCollector  from src.taipy.config.checker._checkers._config_checker import _ConfigChecker      class CheckerForTest(_ConfigChecker):      def _check(self) -> IssueCollector:          return self._collector


from copy import copy  from typing import Any, Dict, List, Optional    from src.taipy.config import Config, Section  from src.taipy.config._config import _Config  from src.taipy.config.common._config_blocker import _ConfigBlocker    from .section_for_tests import SectionForTest      class SectionOfSectionsListForTest(Section):      name = "list_section_name"      _MY_ATTRIBUTE_KEY = "attribute"      _SECTIONS_LIST_KEY = "sections_list"        def __init__(self, id: str, attribute: Any = None, sections_list: List = None, **properties):          self._attribute = attribute          self._sections_list = sections_list if sections_list else []          super().__init__(id, **properties)        def __copy__(self):          return SectionOfSectionsListForTest(              self.id, self._attribute, copy(self._sections_list), **copy(self._properties)          )        @property      def attribute(self):          return self._replace_templates(self._attribute)        @attribute.setter  # type: ignore      @_ConfigBlocker._check()      def attribute(self, val):          self._attribute = val        @property      def sections_list(self):          return list(self._sections_list)        @sections_list.setter  # type: ignore      @_ConfigBlocker._check()      def sections_list(self, val):          self._sections_list = val        def _clean(self):          self._attribute = None          self._sections_list = []          self._properties.clear()        def _to_dict(self):          as_dict = {}          if self._attribute is not None:              as_dict[self._MY_ATTRIBUTE_KEY] = self._attribute          if self._sections_list:              as_dict[self._SECTIONS_LIST_KEY] = self._sections_list          as_dict.update(self._properties)          return as_dict        @classmethod      def _from_dict(cls, as_dict: Dict[str, Any], id: str, config: Optional[_Config] = None):          as_dict.pop(cls._ID_KEY, id)          attribute = as_dict.pop(cls._MY_ATTRIBUTE_KEY, None)          section_configs = config._sections.get(SectionForTest.name, None) or []  # type: ignore          sections_list = []          if inputs_as_str := as_dict.pop(cls._SECTIONS_LIST_KEY, None):              for section_id in inputs_as_str:                  if section_id in section_configs:                      sections_list.append(section_configs[section_id])                  else:                      sections_list.append(section_id)          return SectionOfSectionsListForTest(id=id, attribute=attribute, sections_list=sections_list, **as_dict)        def _update(self, as_dict: Dict[str, Any], default_section=None):          self._attribute = as_dict.pop(self._MY_ATTRIBUTE_KEY, self._attribute)          if self._attribute is None and default_section:              self._attribute = default_section._attribute          self._sections_list = as_dict.pop(self._SECTIONS_LIST_KEY, self._sections_list)          if self._sections_list is None and default_section:              self._sections_list = default_section._sections_list          self._properties.update(as_dict)          if default_section:              self._properties = {**default_section.properties, **self._properties}        @staticmethod      def _configure(id: str, attribute: str, sections_list: List = None, **properties):          section = SectionOfSectionsListForTest(id, attribute, sections_list, **properties)          Config._register(section)          return Config.sections[SectionOfSectionsListForTest.name][id]


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


import os  import tempfile      class NamedTemporaryFile:      def __init__(self, content=None):          with tempfile.NamedTemporaryFile("w", delete=False) as fd:              if content:                  fd.write(content)              self.filename = fd.name        def read(self):          with open(self.filename, "r") as fp:              return fp.read()        def __del__(self):          os.unlink(self.filename)


from copy import copy  from typing import Any, Dict, Optional    from src.taipy.config import Config, Section  from src.taipy.config._config import _Config  from src.taipy.config.common._config_blocker import _ConfigBlocker      class SectionForTest(Section):      name = "section_name"      _MY_ATTRIBUTE_KEY = "attribute"        def __init__(self, id: str, attribute: Any = None, **properties):          self._attribute = attribute          super().__init__(id, **properties)        def __copy__(self):          return SectionForTest(self.id, self._attribute, **copy(self._properties))        @property      def attribute(self):          return self._replace_templates(self._attribute)        @attribute.setter  # type: ignore      @_ConfigBlocker._check()      def attribute(self, val):          self._attribute = val        def _clean(self):          self._attribute = None          self._properties.clear()        def _to_dict(self):          as_dict = {}          if self._attribute is not None:              as_dict[self._MY_ATTRIBUTE_KEY] = self._attribute          as_dict.update(self._properties)          return as_dict        @classmethod      def _from_dict(cls, as_dict: Dict[str, Any], id: str, config: Optional[_Config] = None):          as_dict.pop(cls._ID_KEY, id)          attribute = as_dict.pop(cls._MY_ATTRIBUTE_KEY, None)          return SectionForTest(id=id, attribute=attribute, **as_dict)        def _update(self, as_dict: Dict[str, Any], default_section=None):          self._attribute = as_dict.pop(self._MY_ATTRIBUTE_KEY, self._attribute)          if self._attribute is None and default_section:              self._attribute = default_section._attribute          self._properties.update(as_dict)          if default_section:              self._properties = {**default_section.properties, **self._properties}        @staticmethod      def _configure(id: str, attribute: str, **properties):          section = SectionForTest(id, attribute, **properties)          Config._register(section)          return Config.sections[SectionForTest.name][id]


from copy import copy  from typing import Any, Dict, Optional    from src.taipy.config import Config  from src.taipy.config._config import _Config  from src.taipy.config.common._config_blocker import _ConfigBlocker  from src.taipy.config.unique_section import UniqueSection      class UniqueSectionForTest(UniqueSection):      name = "unique_section_name"      _MY_ATTRIBUTE_KEY = "attribute"        def __init__(self, attribute: str = None, **properties):          self._attribute = attribute          super().__init__(**properties)        def __copy__(self):          return UniqueSectionForTest(self._attribute, **copy(self._properties))        @property      def attribute(self):          return self._replace_templates(self._attribute)        @attribute.setter  # type: ignore      @_ConfigBlocker._check()      def attribute(self, val):          self._attribute = val        def _clean(self):          self._attribute = None          self._properties.clear()        def _to_dict(self):          as_dict = {}          if self._attribute is not None:              as_dict[self._MY_ATTRIBUTE_KEY] = self._attribute          as_dict.update(self._properties)          return as_dict        @classmethod      def _from_dict(cls, as_dict: Dict[str, Any], id=None, config: Optional[_Config] = None):          as_dict.pop(cls._ID_KEY, None)          attribute = as_dict.pop(cls._MY_ATTRIBUTE_KEY, None)          return UniqueSectionForTest(attribute=attribute, **as_dict)        def _update(self, as_dict: Dict[str, Any], default_section=None):          self._attribute = as_dict.pop(self._MY_ATTRIBUTE_KEY, self._attribute)          if self._attribute is None and default_section:              self._attribute = default_section._attribute          self._properties.update(as_dict)          if default_section:              self._properties = {**default_section.properties, **self._properties}        @staticmethod      def _configure(attribute: str, **properties):          section = UniqueSectionForTest(attribute, **properties)          Config._register(section)          return Config.unique_sections[UniqueSectionForTest.name]


import pytest    from src.taipy.config.common._validate_id import _validate_id  from src.taipy.config.exceptions.exceptions import InvalidConfigurationId      class TestId:      def test_validate_id(self):          s = _validate_id("foo")          assert s == "foo"          with pytest.raises(InvalidConfigurationId):              _validate_id("1foo")          with pytest.raises(InvalidConfigurationId):              _validate_id("foo bar")          with pytest.raises(InvalidConfigurationId):              _validate_id("foo/foo$")          with pytest.raises(InvalidConfigurationId):              _validate_id("")          with pytest.raises(InvalidConfigurationId):              _validate_id(" ")          with pytest.raises(InvalidConfigurationId):              _validate_id("class")          with pytest.raises(InvalidConfigurationId):              _validate_id("def")          with pytest.raises(InvalidConfigurationId):              _validate_id("with")          with pytest.raises(InvalidConfigurationId):              _validate_id("CYCLE")          with pytest.raises(InvalidConfigurationId):              _validate_id("SCENARIO")          with pytest.raises(InvalidConfigurationId):              _validate_id("SEQUENCE")          with pytest.raises(InvalidConfigurationId):              _validate_id("TASK")          with pytest.raises(InvalidConfigurationId):              _validate_id("DATANODE")


import pytest    from src.taipy.config.common.scope import Scope      def test_scope():      # Test __ge__ method      assert Scope.GLOBAL >= Scope.GLOBAL      assert Scope.GLOBAL >= Scope.CYCLE      assert Scope.CYCLE >= Scope.CYCLE      assert Scope.GLOBAL >= Scope.SCENARIO      assert Scope.CYCLE >= Scope.SCENARIO      assert Scope.SCENARIO >= Scope.SCENARIO      with pytest.raises(TypeError):          assert Scope.SCENARIO >= "testing string"        # Test __gt__ method      assert Scope.GLOBAL > Scope.CYCLE      assert Scope.GLOBAL > Scope.SCENARIO      assert Scope.CYCLE > Scope.SCENARIO      with pytest.raises(TypeError):          assert Scope.SCENARIO > "testing string"        # Test __le__ method      assert Scope.GLOBAL <= Scope.GLOBAL      assert Scope.CYCLE <= Scope.GLOBAL      assert Scope.CYCLE <= Scope.CYCLE      assert Scope.SCENARIO <= Scope.GLOBAL      assert Scope.SCENARIO <= Scope.CYCLE      assert Scope.SCENARIO <= Scope.SCENARIO      with pytest.raises(TypeError):          assert Scope.SCENARIO <= "testing string"        # Test __lt__ method      assert Scope.SCENARIO < Scope.GLOBAL      assert Scope.SCENARIO < Scope.GLOBAL      assert Scope.SCENARIO < Scope.CYCLE      with pytest.raises(TypeError):          assert Scope.SCENARIO < "testing string"


import argparse  import re  import sys    import pytest    from src.taipy._cli._base_cli import _CLI    if sys.version_info >= (3, 10):      argparse_options_str = "options:"  else:      argparse_options_str = "optional arguments:"      def preprocess_stdout(stdout):      stdout = stdout.replace("\n", " ").replace("\t", " ")      return re.sub(" +", " ", stdout)      def remove_subparser(name: str):      """Remove a subparser from argparse."""      _CLI._sub_taipyparsers.pop(name, None)        if _CLI._subparser_action:          _CLI._subparser_action._name_parser_map.pop(name, None)            for action in _CLI._subparser_action._choices_actions:              if action.dest == name:                  _CLI._subparser_action._choices_actions.remove(action)      @pytest.fixture(autouse=True, scope="function")  def clean_argparser():      _CLI._parser = argparse.ArgumentParser(conflict_handler="resolve")      _CLI._arg_groups = {}      subcommands = list(_CLI._sub_taipyparsers.keys())      for subcommand in subcommands:          remove_subparser(subcommand)        yield      def test_subparser(capfd):      subcommand_1 = _CLI._add_subparser("subcommand_1", help="subcommand_1 help")      subcommand_1.add_argument("--foo", "-f", help="foo help")      subcommand_1.add_argument("--bar", "-b", help="bar help")        subcommand_2 = _CLI._add_subparser("subcommand_2", help="subcommand_2 help")      subcommand_2.add_argument("--doo", "-d", help="doo help")      subcommand_2.add_argument("--baz", "-z", help="baz help")        expected_subcommand_1_help_message = f"""subcommand_1 [-h] [--foo FOO] [--bar BAR]    {argparse_options_str}    -h, --help         show this help message and exit    --foo FOO, -f FOO  foo help    --bar BAR, -b BAR  bar help      """        subcommand_1.print_help()      stdout, _ = capfd.readouterr()      assert preprocess_stdout(expected_subcommand_1_help_message) in preprocess_stdout(stdout)        expected_subcommand_2_help_message = f"""subcommand_2 [-h] [--doo DOO] [--baz BAZ]    {argparse_options_str}    -h, --help         show this help message and exit    --doo DOO, -d DOO  doo help    --baz BAZ, -z BAZ  baz help      """        subcommand_2.print_help()      stdout, _ = capfd.readouterr()      assert preprocess_stdout(expected_subcommand_2_help_message) in preprocess_stdout(stdout)      def test_duplicate_subcommand():      subcommand_1 = _CLI._add_subparser("subcommand_1", help="subcommand_1 help")      subcommand_1.add_argument("--foo", "-f", help="foo help")        subcommand_2 = _CLI._add_subparser("subcommand_1", help="subcommand_2 help")      subcommand_2.add_argument("--bar", "-b", help="bar help")        # The title of subcommand_2 is duplicated with  subcommand_1, and therefore      # there will be no new subcommand created      assert len(_CLI._sub_taipyparsers) == 1      def test_groupparser(capfd):      group_1 = _CLI._add_groupparser("group_1", "group_1 desc")      group_1.add_argument("--foo", "-f", help="foo help")      group_1.add_argument("--bar", "-b", help="bar help")        group_2 = _CLI._add_groupparser("group_2", "group_2 desc")      group_2.add_argument("--doo", "-d", help="doo help")      group_2.add_argument("--baz", "-z", help="baz help")        expected_help_message = """  group_1:    group_1 desc      --foo FOO, -f FOO  foo help    --bar BAR, -b BAR  bar help    group_2:    group_2 desc      --doo DOO, -d DOO  doo help    --baz BAZ, -z BAZ  baz help      """.strip()        _CLI._parser.print_help()      stdout, _ = capfd.readouterr()        assert expected_help_message in stdout      def test_duplicate_group():      group_1 = _CLI._add_groupparser("group_1", "group_1 desc")      group_1.add_argument("--foo", "-f", help="foo help")        group_2 = _CLI._add_groupparser("group_1", "group_2 desc")      group_2.add_argument("--bar", "-b", help="bar help")        # The title of group_2 is duplicated with  group_1, and therefore      # there will be no new group created      assert len(_CLI._arg_groups) == 1


import pytest    from src.taipy.config.common._classproperty import _Classproperty      class TestClassProperty:      def test_class_property(self):          class TestClass:              @_Classproperty              def test_property(cls):                  return "test_property"            assert TestClass.test_property == "test_property"          assert TestClass().test_property == "test_property"          with pytest.raises(TypeError):              TestClass.test_property()


import os  from unittest import mock    import pytest    from src.taipy.config.config import Config  from src.taipy.config.exceptions.exceptions import ConfigurationUpdateBlocked      def test_global_config_with_env_variable_value():      with mock.patch.dict(os.environ, {"FOO": "bar", "BAZ": "qux"}):          Config.configure_global_app(foo="ENV[FOO]", bar="ENV[BAZ]")          assert Config.global_config.foo == "bar"          assert Config.global_config.bar == "qux"      def test_default_global_app_config():      global_config = Config.global_config      assert global_config is not None      assert not global_config.notification      assert len(global_config.properties) == 0      def test_block_update_global_app_config():      Config.block_update()        with pytest.raises(ConfigurationUpdateBlocked):          Config.configure_global_app(foo="bar")        with pytest.raises(ConfigurationUpdateBlocked):          Config.global_config.properties = {"foo": "bar"}        # Test if the global_config stay as default      assert Config.global_config.foo is None      assert len(Config.global_config.properties) == 0


import argparse  import re  from unittest.mock import patch    import pytest    from src.taipy._entrypoint import _entrypoint  from taipy._cli._base_cli import _CLI      def preprocess_stdout(stdout):      stdout = stdout.replace("\n", " ").replace("\t", " ")      return re.sub(" +", " ", stdout)      def remove_subparser(name: str):      """Remove a subparser from the _CLI class."""      _CLI._sub_taipyparsers.pop(name, None)        if _CLI._subparser_action:          _CLI._subparser_action._name_parser_map.pop(name, None)            for action in _CLI._subparser_action._choices_actions:              if action.dest == name:                  _CLI._subparser_action._choices_actions.remove(action)      @pytest.fixture(autouse=True, scope="function")  def clean_argparser():      _CLI._parser = argparse.ArgumentParser(conflict_handler="resolve")      _CLI._subparser_action = None      _CLI._arg_groups = {}      subcommands = list(_CLI._sub_taipyparsers.keys())      for subcommand in subcommands:          remove_subparser(subcommand)        yield      expected_help = """{run,manage-versions,create,migrate,help} ...    positional arguments:    {run,manage-versions,create,migrate,help}      run                 Run a Taipy application.      manage-versions     Taipy version control system.      create              Create a new Taipy application.      migrate             Migrate entities created from old taipy versions to be compatible with the current taipy      version. The entity migration should be performed only after updating taipy code to the current version.      help                Show the Taipy help message.  """      def test_taipy_command_alone_print_help(capsys):      with patch("sys.argv", ["prog"]):          _entrypoint()          out, _ = capsys.readouterr()          assert preprocess_stdout(expected_help) in preprocess_stdout(out)      def test_taipy_help_command(capsys):      with patch("sys.argv", ["prog", "help"]):          with pytest.raises(SystemExit):              _entrypoint()          out, _ = capsys.readouterr()          assert preprocess_stdout(expected_help) in preprocess_stdout(out)      def test_help_non_existed_command(caplog):      with patch("sys.argv", ["prog", "help", "non_existed_command"]):          with pytest.raises(SystemExit):              _entrypoint()          assert "non_existed_command is not a valid command." in caplog.text      def test_taipy_create_help(capsys):      expected_help = "create [-h] [--template"        with patch("sys.argv", ["prog", "help", "create"]):          with pytest.raises(SystemExit):              _entrypoint()          out, _ = capsys.readouterr()          assert preprocess_stdout(expected_help) in preprocess_stdout(out)


import os  import sys  from importlib.util import find_spec  from pathlib import Path    import pandas as pd  # type: ignore  import pytest  from flask import Flask, g      def pytest_configure(config):      if (find_spec("src") and find_spec("src.taipy")) and (not find_spec("taipy") or not find_spec("taipy.gui")):          import src.taipy.gui          import src.taipy.gui._renderers.builder          import src.taipy.gui._warnings          import src.taipy.gui.builder          import src.taipy.gui.data.decimator.lttb          import src.taipy.gui.data.decimator.minmax          import src.taipy.gui.data.decimator.rdp          import src.taipy.gui.data.decimator.scatter_decimator          import src.taipy.gui.data.utils          import src.taipy.gui.extension          import src.taipy.gui.utils._map_dict          import src.taipy.gui.utils._variable_directory          import src.taipy.gui.utils.expr_var_name            sys.modules["taipy.gui._warnings"] = sys.modules["src.taipy.gui._warnings"]          sys.modules["taipy.gui._renderers.builder"] = sys.modules["src.taipy.gui._renderers.builder"]          sys.modules["taipy.gui.utils._variable_directory"] = sys.modules["src.taipy.gui.utils._variable_directory"]          sys.modules["taipy.gui.utils.expr_var_name"] = sys.modules["src.taipy.gui.utils.expr_var_name"]          sys.modules["taipy.gui.utils._map_dict"] = sys.modules["src.taipy.gui.utils._map_dict"]          sys.modules["taipy.gui.extension"] = sys.modules["src.taipy.gui.extension"]          sys.modules["taipy.gui.data.utils"] = sys.modules["src.taipy.gui.data.utils"]          sys.modules["taipy.gui.data.decimator.lttb"] = sys.modules["src.taipy.gui.data.decimator.lttb"]          sys.modules["taipy.gui.data.decimator.rdp"] = sys.modules["src.taipy.gui.data.decimator.rdp"]          sys.modules["taipy.gui.data.decimator.minmax"] = sys.modules["src.taipy.gui.data.decimator.minmax"]          sys.modules["taipy.gui.data.decimator.scatter_decimator"] = sys.modules[              "src.taipy.gui.data.decimator.scatter_decimator"          ]          sys.modules["taipy.gui"] = sys.modules["src.taipy.gui"]          sys.modules["taipy.gui.builder"] = sys.modules["src.taipy.gui.builder"]      csv = pd.read_csv(      f"{Path(Path(__file__).parent.resolve())}{os.path.sep}current-covid-patients-hospital.csv", parse_dates=["Day"]  )  small_dataframe_data = {"name": ["A", "B", "C"], "value": [1, 2, 3]}      @pytest.fixture(scope="function")  def csvdata():      yield csv      @pytest.fixture(scope="function")  def small_dataframe():      yield small_dataframe_data      @pytest.fixture(scope="function")  def gui(helpers):      from taipy.gui import Gui        gui = Gui()      yield gui      # Delete Gui instance and state of some classes after each test      gui.stop()      helpers.test_cleanup()      @pytest.fixture  def helpers():      from .helpers import Helpers        return Helpers      @pytest.fixture  def test_client():      flask_app = Flask("Test App")        # Create a test client using the Flask application configured for testing      with flask_app.test_client() as testing_client:          # Establish an application context          with flask_app.app_context():              g.client_id = "test client id"              yield testing_client  # this is where the testing happens!


import inspect    from taipy.gui import Gui, Html      def test_simple_html(gui: Gui, helpers):      # html_string = "
test
<taipy:field value=\"test\"/>"      html_string = "
test
"      gui._set_frame(inspect.currentframe())      gui.add_page("test", Html(html_string))      gui.run(run_server=False)      client = gui._server.test_client()      jsx = client.get("/taipy-jsx/test").json["jsx"]      assert jsx == "
test
"


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


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


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


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


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


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


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


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


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


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


import inspect  import warnings    from taipy.gui import Gui, Markdown, State, navigate      def test_navigate(gui: Gui, helpers):      def navigate_to(state: State):          navigate(state, "test")        with warnings.catch_warnings(record=True):          gui._set_frame(inspect.currentframe())          gui.add_page("test", Markdown("#This is a page"))          gui.run(run_server=False)          client = gui._server.test_client()          # WS client and emit          ws_client = gui._server._ws.test_client(gui._server.get_flask())          # Get the jsx once so that the page will be evaluated -> variable will be registered          sid = helpers.create_scope_and_get_sid(gui)          client.get(f"/taipy-jsx/test/?client_id={sid}")          ws_client.emit("message", {"client_id": sid, "type": "A", "name": "my_button", "payload": "navigate_to"})          # assert for received message (message that would be sent to the front-end client)          assert ws_client.get_received()      def test_navigate_to_no_route(gui: Gui, helpers):      def navigate_to(state: State):          navigate(state, "toto")        with warnings.catch_warnings(record=True):          gui._set_frame(inspect.currentframe())          gui.add_page("test", Markdown("#This is a page"))          gui.run(run_server=False)          client = gui._server.test_client()          # WS client and emit          ws_client = gui._server._ws.test_client(gui._server.get_flask())          # Get the jsx once so that the page will be evaluated -> variable will be registered          sid = helpers.create_scope_and_get_sid(gui)          client.get(f"/taipy-jsx/test/?client_id={sid}")          ws_client.emit("message", {"client_id": sid, "type": "A", "name": "my_button", "payload": "navigate_to"})          # assert for received message (message that would be sent to the front-end client)          assert not ws_client.get_received()      def test_on_navigate_to_inexistant(gui: Gui, helpers):      def on_navigate(state: State, page: str):          return "test2" if page == "test" else page        with warnings.catch_warnings(record=True) as records:          gui._set_frame(inspect.currentframe())          gui.add_page("test", Markdown("#This is a page"))          gui.run(run_server=False)          client = gui._server.test_client()          # Get the jsx once so that the page will be evaluated -> variable will be registered          sid = helpers.create_scope_and_get_sid(gui)          client.get(f"/taipy-jsx/test?client_id={sid}")          warns = helpers.get_taipy_warnings(records)          assert len(warns) == 1          text = warns[0].message.args[0] if isinstance(warns[0].message, Warning) else warns[0].message          assert text == 'Cannot navigate to "test2": unknown page.'      def test_on_navigate_to_existant(gui: Gui, helpers):      def on_navigate(state: State, page: str):          return "test2" if page == "test1" else page        with warnings.catch_warnings(record=True):          gui._set_frame(inspect.currentframe())          gui.add_page("test1", Markdown("#This is a page test1"))          gui.add_page("test2", Markdown("#This is a page test2"))          gui.run(run_server=False)          client = gui._server.test_client()          # Get the jsx once so that the page will be evaluated -> variable will be registered          sid = helpers.create_scope_and_get_sid(gui)          content = client.get(f"/taipy-jsx/test1?client_id={sid}")          assert content.status_code == 302


import inspect    import pandas as pd  # type: ignore    from taipy.gui import Gui      def test_expression_text_control_str(gui: Gui, test_client, helpers):      gui._bind_var_val("x", "Hello World!")      md_string = "<|{x}|>"      expected_list = ["<Field", 'dataType="str"', 'defaultValue="Hello World!"', "value={tpec_TpExPr_x_TPMDL_0}"]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_text_control_int(gui: Gui, test_client, helpers):      gui._bind_var_val("x", 10)      md_string = "<|{x}|>"      expected_list = ["<Field", 'dataType="int"', 'defaultValue="10"', "value={tpec_TpExPr_x_TPMDL_0}"]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_text_control_1(gui: Gui, test_client, helpers):      gui._set_frame(inspect.currentframe())      gui._bind_var_val("x", 10)      gui._bind_var_val("y", 20)      md_string = "<|{x + y}|>"      expected_list = [          "<Field",          'dataType="int"',          'defaultValue="30"',          "value={tp_TpExPr_x_y_TPMDL_0_0}",      ]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_text_control_2(gui: Gui, test_client, helpers):      gui._set_frame(inspect.currentframe())      gui._bind_var_val("x", 10)      gui._bind_var_val("y", 20)      md_string = "<|x + y = {x + y}|>"      expected_list = [          "<Field",          'dataType="str"',          'defaultValue="x + y = 30"',          "value={tp_TpExPr_x_y_x_y_TPMDL_0_0}",      ]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_text_control_3(gui: Gui, test_client, helpers):      gui._set_frame(inspect.currentframe())      gui._bind_var_val("x", "Mickey Mouse")      gui._bind_var_val("y", "Donald Duck")      md_string = "<|Hello {x} and {y}|>"      expected_list = [          "<Field",          'dataType="str"',          'defaultValue="Hello Mickey Mouse and Donald Duck"',          "value={tp_TpExPr_Hello_x_and_y_TPMDL_0_0}",      ]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_text_gt_operator(gui: Gui, test_client, helpers):      gui._set_frame(inspect.currentframe())      gui._bind_var_val("x", 0)      md_string = "<|{x > 0}|>"      expected_list = [          "<Field",          'dataType="bool"',          'defaultValue="false"',          "value={tp_TpExPr_x_0_TPMDL_0_0}",      ]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_button_control(gui: Gui, test_client, helpers):      gui._bind_var_val("label", "A button label")      md_string = "<|button|label={label}|>"      expected_list = ["<Button", 'defaultLabel="A button label"', "label={tpec_TpExPr_label_TPMDL_0}"]      helpers.test_control_md(gui, md_string, expected_list)      def test_expression_table_control(gui: Gui, test_client, helpers):      gui._set_frame(inspect.currentframe())      gui._bind_var_val("pd", pd)      gui._bind_var_val("series_1", pd.Series(["a", "b", "c"], name="Letters"))      gui._bind_var_val("series_2", pd.Series([1, 2, 3], name="Numbers"))      md_string = "<|{pd.concat([series_1, series_2], axis=1)}|table|columns=Letters;Numbers|>"      expected_list = [          "<Table",          'defaultColumns="{"Letters": {"index": 0, "type": "object", "dfid": "Letters"}, "Numbers": {"index": 1, "type": "int", "dfid": "Numbers"}}"',          'updateVarName="_TpD_tp_TpExPr_pd_concat_series_1_series_2_axis_1_TPMDL_0_0"',          "data={_TpD_tp_TpExPr_pd_concat_series_1_series_2_axis_1_TPMDL_0_0}",      ]      helpers.test_control_md(gui, md_string, expected_list)      assert isinstance(gui._get_data_scope().tp_TpExPr_pd_concat_series_1_series_2_axis_1_TPMDL_0_0, pd.DataFrame)      def test_lambda_expression_selector(gui: Gui, test_client, helpers):      gui._bind_var_val(          "lov",          [              {"id": "1", "name": "scenario 1"},              {"id": "3", "name": "scenario 3"},              {"id": "2", "name": "scenario 2"},          ],      )      gui._bind_var_val("sel", {"id": "1", "name": "scenario 1"})      md_string = "<|{sel}|selector|lov={lov}|type=test|adapter={lambda elt: (elt['id'], elt['name'])}|>"      expected_list = [          "<Selector",          'defaultLov="[["1", "scenario 1"], ["3", "scenario 3"], ["2", "scenario 2"]]"',          'defaultValue="["1"]"',          'updateVars="lov=_TpL_tpec_TpExPr_lov_TPMDL_0"',          "lov={_TpL_tpec_TpExPr_lov_TPMDL_0}",          'updateVarName="_TpLv_tpec_TpExPr_sel_TPMDL_0"',          "value={_TpLv_tpec_TpExPr_sel_TPMDL_0}",      ]      helpers.test_control_md(gui, md_string, expected_list)


import numpy as np  import pandas as pd    from taipy.gui.data.decimator.lttb import LTTB  from taipy.gui.data.decimator.minmax import MinMaxDecimator  from taipy.gui.data.decimator.rdp import RDP  from taipy.gui.data.decimator.scatter_decimator import ScatterDecimator  from taipy.gui.data.utils import _df_data_filter      def test_data_filter_1(csvdata):      df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", MinMaxDecimator(100), {}, False)      assert df.shape[0] == 100      def test_data_filter_2(csvdata):      df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", LTTB(100), {}, False)      assert df.shape[0] == 100      def test_data_filter_3(csvdata):      df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", RDP(n_out=100), {}, False)      assert df.shape[0] == 100      def test_data_filter_4(csvdata):      df, _ = _df_data_filter(csvdata[:1500], None, "Daily hospital occupancy", "", RDP(epsilon=100), {}, False)      assert df.shape[0] == 18      def test_data_filter_5(csvdata):      df, _ = _df_data_filter(          csvdata[:1500], None, "Daily hospital occupancy", "", ScatterDecimator(), {"width": 200, "height": 100}, False      )      assert df.shape[0] == 1150


#  # 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    from .state_asset.page1 import get_a, md_page1, set_a      def test_state(gui: Gui):      a = 10  # noqa: F841      gui._set_frame(inspect.currentframe())      gui.add_page("page1", md_page1)      gui.run(run_server=False, single_client=True)      state = gui._Gui__state      with gui.get_flask_app().app_context():          assert state.a == 10          assert state["page1"].a == 20          assert state["tests.taipy.gui.gui_specific.state_asset.page1"].a == 20          assert state._gui == gui          with pytest.raises(Exception) as e:              state.b          assert e.value.args[0] == "Variable 'b' is not defined."            with pytest.raises(Exception) as e:              state.b = 10          assert e.value.args[0] == "Variable 'b' is not accessible."            with pytest.raises(Exception) as e:              state._taipy_p1          assert e.value.args[0] == "Variable '_taipy_p1' is protected and is not accessible."            with pytest.raises(Exception) as e:              state._taipy_p1 = 10          assert e.value.args[0] == "Variable '_taipy_p1' is not accessible."            assert state._get_placeholder("_taipy_p1") is None            state._set_placeholder("_taipy_p1", 10)            assert state._get_placeholder("_taipy_p1") == 10            assert state._get_placeholder_attrs() == (              "_taipy_p1",              "_current_context",          )            assert get_a(state) == 20            set_a(state, 30)            assert get_a(state) == 30


import pytest    from taipy.gui import Gui  from taipy.gui.utils._locals_context import _LocalsContext      def test_locals_context(gui: Gui):      lc = _LocalsContext()      gui.run(run_server=False)      with gui.get_flask_app().app_context():          with pytest.raises(KeyError):              lc.get_default()          current_locals = locals()          lc.set_default(current_locals)          assert lc.get_default() == current_locals          temp_locals = {"__main__": "test"}          lc.add("test", temp_locals)          assert lc.get_context() is None          assert lc.get_locals() == current_locals          with lc.set_locals_context("test"):              assert lc.get_context() == "test"              assert lc.get_locals() == temp_locals          assert lc.get_context() is None          assert lc.get_locals() == current_locals          assert lc.is_default() is True          assert "__main__" in lc.get_all_keys()


import inspect    from taipy.gui.utils.get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var    x = 10      def test_get_module_name():      assert "tests.taipy.gui.gui_specific.test_get_module_name" == _get_module_name_from_frame(inspect.currentframe())      def test_get_module_name_imported_var():      assert "tests.taipy.gui.gui_specific.test_get_module_name" == _get_module_name_from_imported_var(          "x", 10, "test_get_module_name"      )      assert "test_get_module_name" == _get_module_name_from_imported_var("x", 11, "test_get_module_name")


import inspect  import os  from pathlib import Path    from taipy.gui import Gui      def test_folder_pages_binding(gui: Gui):      folder_path = f"{Path(Path(__file__).parent.resolve())}{os.path.sep}sample_assets"      gui._set_frame(inspect.currentframe())      gui.add_pages(folder_path)      gui.run(run_server=False)      assert len(gui._config.routes) == 3  # 2 files -> 2 routes + 1 default route      assert len(gui._config.pages) == 3  # 2 files -> 2 pages + 1 default page


import inspect  import json  import warnings    from taipy.gui import Gui      def test_render_route(gui: Gui):      gui._set_frame(inspect.currentframe())      gui.add_page("page1", "# first page")      gui.add_page("page2", "# second page")      gui.run(run_server=False)      with warnings.catch_warnings(record=True):          client = gui._server.test_client()          response = client.get("/taipy-init")          response_data = json.loads(response.get_data().decode("utf-8", "ignore"))          assert response.status_code == 200          assert isinstance(response_data, dict)          assert isinstance(response_data["locations"], dict)          assert "/page1" in response_data["locations"]          assert "/page2" in response_data["locations"]          assert "/" in response_data["locations"]          assert response_data["locations"] == {"/": "/TaiPy_root_page", "/page1": "/page1", "/page2": "/page2"}