From 7d8439040408093a48725f426a3ea726285147b3 Mon Sep 17 00:00:00 2001 From: Julian Stirling Date: Thu, 14 May 2026 11:24:05 +0100 Subject: [PATCH] Clean up temporary data dir in LabThingsTestEnv after test --- tests/shared_utils/lt_test_utils.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/shared_utils/lt_test_utils.py b/tests/shared_utils/lt_test_utils.py index 6e272c1d..5ceabe4c 100644 --- a/tests/shared_utils/lt_test_utils.py +++ b/tests/shared_utils/lt_test_utils.py @@ -42,24 +42,28 @@ class LabThingsTestEnv: as a context manager: :param things: The thing configuration dictionary used to initialise the server. - :param settings_folder: The settings folder to use. + :param settings_folder: The settings folder to use. If None a tempdir is created + for this. + :param application_config: The application configuration dictionary. If None is + supplied then "data_folder" is set to a temporary directory. """ self._server: Optional[lt.ThingServer] self._test_client: Optional[TestClient] self._things_config = things self._settings_folder = settings_folder - # Labthings requires an application config for the data_folder - if application_config: - self._application_config = application_config - else: - self._application_config = {"data_folder": tempfile.TemporaryDirectory()} - self._tmp_dir_obj: Optional[tempfile.TemporaryDirectory] = None + self._application_config = application_config + self._settings_tmp_dir: Optional[tempfile.TemporaryDirectory] = None + self._data_tmp_dir: Optional[tempfile.TemporaryDirectory] = None def __enter__(self) -> Self: """Create server and run it in the TestClient.""" + # Any OFMThings require an application config for the data_folder + if self._application_config is None: + self._data_tmp_dir = tempfile.TemporaryDirectory() + self._application_config = {"data_folder": self._data_tmp_dir} if self._settings_folder is None: - self._tmp_dir_obj = tempfile.TemporaryDirectory() - self._settings_folder = self._tmp_dir_obj.name + self._settings_tmp_dir = tempfile.TemporaryDirectory() + self._settings_folder = self._settings_tmp_dir.name self._server = lt.ThingServer( things=self._things_config, settings_folder=self._settings_folder, @@ -77,8 +81,10 @@ class LabThingsTestEnv: ) -> None: """Close the TestClient and cleanup.""" self._test_client.__exit__(exc_type, exc_value, traceback) - if self._tmp_dir_obj is not None: - self._tmp_dir_obj.cleanup() + if self._settings_tmp_dir is not None: + self._settings_tmp_dir.cleanup() + if self._data_tmp_dir is not None: + self._data_tmp_dir.cleanup() @property def server(self) -> lt.ThingServer: