From 1f4e47f9eb8034abcfe583b59577ab7b14b6e5cb Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 24 Nov 2026 21:13:06 +0000 Subject: [PATCH] FIX: Load an updated data file only when it was published later When a watched file changes or a download finishes, the data update service reads the published date in the new file's header, where the engine offers get_date_published_from_file, and loads the file only when that date is a later day than the data in use. A file that is not newer is left alone and the check is reported as AUTO_UPDATE_NOT_NEEDED. A download is compared before it replaces the data file, and is deleted when it is not newer. The Device Detection and IP Intelligence on-premise engines read the date through the native getPublishedTimeFromFile. Their watcher tests and update examples now expect a copy of the same file to be reported as not needed. Closes #280 --- .../onpremise/datafileupdate_console.py | 20 +- .../devicedetection_onpremise.py | 21 ++ .../tests/test_watcher_without_licence_key.py | 6 +- .../onpremise/datafileupdate_console.py | 16 +- .../ipintelligence_onpremise.py | 21 ++ .../tests/test_watcher_without_licence_key.py | 6 +- .../src/fiftyone_pipeline_engines/datafile.py | 2 +- .../datafile_update_service.py | 135 +++++++- .../tests/test_datafile_published_date.py | 322 ++++++++++++++++++ 9 files changed, 520 insertions(+), 29 deletions(-) create mode 100644 pipeline/fiftyone_pipeline_engines/tests/test_datafile_published_date.py diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py index c5457ed8..b8dc7b4c 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py @@ -86,8 +86,9 @@ # # # File System Watcher # You can configure the pipeline builder to watch for changes to the currently loaded device -# detection data file, and to replace the file currently in use with the new one. This is -# useful, for example, if you wish to download and update the device detection file "manually" - +# detection data file, and to replace the data currently in use with the new file when the new +# file was published later. This is useful, for example, if you wish to download and update the +# device detection file "manually" - # i.e. you would download it then drop it into place with the same path as the currently loaded # file. That location is checked periodically (by default every 30 mins) and this frequency can be # configured. @@ -399,7 +400,8 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non pipeline = DeviceDetectionPipelineBuilder( # specify the filename for the data file. When using update on start-up # the file need not exist, but the directory it is in must exist. - # Any file that is present is overwritten. Because the file will be + # A file that is present is overwritten by a download published + # later. Because the file may be # overwritten the pipeline must be configured to copy the supplied # file to a temporary file (create_temp_copy parameter == True). data_file_path = data_file, @@ -417,8 +419,8 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non update_on_start = True, # Enable automatic updates once the pipeline has started auto_update = True, - # Watch the data file on disk and refresh the engine - # as soon as that file is updated. + # Watch the data file on disk and refresh the engine as + # soon as a file published later is put in its place. file_system_watcher=True, # The product the 51Degrees distributor is asked for, which # is named only when this example is given one. With none @@ -438,15 +440,15 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non if update_event.status == UpdateStatus.AUTO_UPDATE_SUCCESS: - output("Modifying downloaded file to trigger reload - please wait for that" + output("Modifying downloaded file to trigger a check - please wait for that" " to complete") # wait for the dataUpdateService to notify us that it has updated update_event.clear() - # it's the same file but changing the file metadata will trigger reload, - # demonstrating that if you download a new file and replace the - # existing one, then it will be loaded + # it's the same file, so changing its time triggers a check that + # reports AUTO_UPDATE_NOT_NEEDED. A file put in place of the + # existing one is loaded only when it was published later. now = datetime.now().timestamp() try: os.utime(data_file, (now, now)) diff --git a/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py b/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py index 4608e3a2..44e802c9 100644 --- a/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py +++ b/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py @@ -21,6 +21,7 @@ # ********************************************************************* from __future__ import absolute_import +import datetime import multiprocessing import os.path @@ -372,6 +373,26 @@ def init_engine(self): for key, property in self.get_metric_properties().items(): self.properties[key] = property + def get_date_published_from_file(self, path): + + """! + Reads the date a data file was published from its header, without + loading the file. The data file update service loads a watched or + downloaded file only when this date is later than that of the data + in use. + @type path: string + @param path: path to the data file + @rtype: date + @return: the date the data file was published + @raise RuntimeError: when the file cannot be opened, is shorter than + its header, holds no valid date, or is not a data file this engine + reads + """ + + published = EngineHashSwig.getPublishedTimeFromFile(path) + return datetime.date( + published.getYear(), published.getMonth(), published.getDay()) + def read_evidence_keys(self): """! diff --git a/device-detection/fiftyone_devicedetection_onpremise/tests/test_watcher_without_licence_key.py b/device-detection/fiftyone_devicedetection_onpremise/tests/test_watcher_without_licence_key.py index 8456ea65..411ec389 100644 --- a/device-detection/fiftyone_devicedetection_onpremise/tests/test_watcher_without_licence_key.py +++ b/device-detection/fiftyone_devicedetection_onpremise/tests/test_watcher_without_licence_key.py @@ -71,7 +71,7 @@ def test_the_watcher_runs_with_no_licence_key(self): self.assertFalse(watched.auto_update) self.assertFalse(watched.update_on_start) - def test_a_replaced_file_is_loaded_with_no_licence_key(self): + def test_a_replaced_file_is_checked_with_no_licence_key(self): service = DataFileUpdateService() service.FILE_SYSTEM_WATCHER_INTERVAL_SECONDS = \ WATCHER_INTERVAL_SECONDS @@ -95,7 +95,9 @@ def on_complete(status, watched): self.assertTrue( reloaded.wait(RELOAD_WAIT_SECONDS), "The watcher did not report the replaced file.") - self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], statuses) + # The copy was published on the same day as the data in use, so it + # is not loaded, whatever its time, and the engine keeps its data. + self.assertEqual([UpdateStatus.AUTO_UPDATE_NOT_NEEDED], statuses) with pipeline.create_flowdata() as flowdata: flowdata.evidence.add("header.user-agent", mobile_ua) diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py index abbe7dfe..267c354a 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py @@ -48,8 +48,8 @@ # # ## Filesystem watcher # Configure the pipeline to watch the loaded data file on disk and reload it -# when it changes (file_system_watcher=True). Useful if you download files -# yourself and drop them into place. +# when a file published later is put in its place (file_system_watcher=True). +# Useful if you download files yourself and drop them into place. # # ## Daily auto-update # Each data file records when the next file is expected. With auto_update @@ -266,8 +266,9 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non # Build the pipeline, configuring it for automatic updates. pipeline = IpIntelligencePipelineBuilder( # The file need not exist when using update on start-up, but its - # directory must. Any file present is overwritten, so the engine - # is configured to use a temporary copy. + # directory must. A file present is overwritten by a download + # published later, so the engine is configured to use a temporary + # copy. data_file_path = data_file, create_temp_data_copy = True, # The Enterprise data file is large, so the LowMemory profile @@ -302,12 +303,13 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non output(f"Update on start-up complete - status - {update_event.status}") if update_event.status == UpdateStatus.AUTO_UPDATE_SUCCESS: - output("Modifying downloaded file to trigger reload - please wait " + output("Modifying downloaded file to trigger a check - please wait " "for that to complete") update_event.clear() - # Touching the file metadata triggers the filesystem watcher, - # demonstrating reload when a new file is dropped into place. + # Touching the file triggers the filesystem watcher. It is the + # same file, so the check reports AUTO_UPDATE_NOT_NEEDED, as only + # a file published later is loaded. now = datetime.now().timestamp() try: os.utime(data_file, (now, now)) diff --git a/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py b/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py index d41f604c..427316df 100644 --- a/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py +++ b/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py @@ -21,6 +21,7 @@ # ********************************************************************* from __future__ import absolute_import +import datetime import multiprocessing import os.path @@ -309,6 +310,26 @@ def init_engine(self): for metric_property_name, metric_property in self.get_metric_properties().items(): self.properties[metric_property_name] = metric_property + def get_date_published_from_file(self, path): + + """! + Reads the date a data file was published from its header, without + loading the file. The data file update service loads a watched or + downloaded file only when this date is later than that of the data + in use. + @type path: string + @param path: path to the data file + @rtype: date + @return: the date the data file was published + @raise RuntimeError: when the file cannot be opened, is shorter than + its header, holds no valid date, or is not a data file this engine + reads + """ + + published = EngineIpiSwig.getPublishedTimeFromFile(path) + return datetime.date( + published.getYear(), published.getMonth(), published.getDay()) + def read_evidence_keys(self): """! diff --git a/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_watcher_without_licence_key.py b/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_watcher_without_licence_key.py index cdaf8b02..a35dc6ee 100644 --- a/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_watcher_without_licence_key.py +++ b/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_watcher_without_licence_key.py @@ -66,7 +66,7 @@ def test_the_watcher_runs_with_no_licence_key(self): self.assertFalse(watched.auto_update) self.assertFalse(watched.update_on_start) - def test_a_changed_file_is_loaded_with_no_licence_key(self): + def test_a_changed_file_is_checked_with_no_licence_key(self): service = DataFileUpdateService() service.FILE_SYSTEM_WATCHER_INTERVAL_SECONDS = \ WATCHER_INTERVAL_SECONDS @@ -93,7 +93,9 @@ def on_complete(status, watched): self.assertTrue( reloaded.wait(RELOAD_WAIT_SECONDS), "The watcher did not report the changed file.") - self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], statuses) + # The file was published on the same day as the data in use, so it + # is not loaded, whatever its time, and the engine keeps its data. + self.assertEqual([UpdateStatus.AUTO_UPDATE_NOT_NEEDED], statuses) with pipeline.create_flowdata() as flowdata: flowdata.evidence.add("query.client-ip", "8.8.8.8") diff --git a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py index 2ad0c757..5ce78861 100644 --- a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py +++ b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py @@ -54,7 +54,7 @@ def __init__(self, flow_element, identifier, update_url_params = None, data = No @type auto_update: bool @param: auto_update: whether to automatically update the datafile when required @type file_system_watcher: bool - @param file_system_watcher: whether to check the datafile's path for changes and update the connected FlowElement's data automatically when the file is changed in the operating system + @param file_system_watcher: whether to check the datafile's path for changes and update the connected FlowElement's data automatically when the file is changed in the operating system. When the FlowElement has a get_date_published_from_file method, a changed or downloaded file is loaded only when the date it gives for the file is later than get_date_published gives for the data in use @type polling_interval: int @param polling_interval: How often to poll for updates to the datafile (minutes) @type update_time_maximum_randomisation : int diff --git a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py index 2a1cf4f3..ae610676 100644 --- a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py +++ b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py @@ -413,7 +413,15 @@ def _update_data_file(self, data_file): # write that failed leaves it with the data it already had and # the update ends there, as it does in .NET and # 51degrees-node. - self._write_data_file(data_file, data) + if self._published_date_reader(data_file) is None: + self._write_data_file(data_file, data) + else: + # A download that is not newer than the data in use replaces + # neither the data file nor the engine's data. + staged = self._stage_data_file(data_file, data, True) + if not self._is_newer_or_discard(data_file, staged): + return UpdateStatus.AUTO_UPDATE_NOT_NEEDED + self._replace_data_file(data_file, staged) else: @@ -604,6 +612,17 @@ def _write_data_file(self, data_file, data): # when the data file asks for one. A failure raises a # DataUpdateException with the message and status of its row of the # errors table, and leaves the file on disk as it was. + self._replace_data_file( + data_file, self._stage_data_file(data_file, data, False)) + + def _stage_data_file(self, data_file, data, apart): + # Write new data to the file that replaces the data file, and answer + # its path. That is a temporary copy when the data file asks for + # one. Otherwise it is a file beside the data file when the data + # must be kept apart until it is known to be newer, and the data + # file itself when not. A failure raises a DataUpdateException with + # the message and status of its row of the errors table, and leaves + # the data file as it was. if data_file.create_temp_copy: if not getattr(data_file, "temp_directory", None): raise DataUpdateException( @@ -614,6 +633,10 @@ def _write_data_file(self, data_file, data): filename = os.path.join( data_file.temp_directory, data_file.identifier + str(time.time())) + elif apart: + filename = os.path.join( + os.path.dirname(data_file.path), + data_file.identifier + str(time.time())) else: filename = data_file.path @@ -634,8 +657,13 @@ def _write_data_file(self, data_file, data): raise DataUpdateException( self._unhandled_message(data_file), UpdateStatus.AUTO_UPDATE_UNKNOWN_ERROR) from e + return filename - if data_file.create_temp_copy: + def _replace_data_file(self, data_file, filename): + # Put the file written by _stage_data_file in place of the data + # file. A failure raises a DataUpdateException with the message and + # status of its row of the errors table. + if filename != data_file.path: try: shutil.move(filename, data_file.path) except (OSError, shutil.Error) as e: @@ -653,6 +681,91 @@ def _write_data_file(self, data_file, data): except OSError: pass + @staticmethod + def _published_date_reader(data_file): + # The method of the data file's engine that reads the published date + # in a data file's header, or None when the engine has none, and a + # new file is then loaded without comparing dates. + return getattr( + getattr(data_file, "flow_element", None), + "get_date_published_from_file", None) + + @staticmethod + def _published_day(moment): + # The day of a published date, in UTC for a time with a zone. A data + # file's header holds a date with no time or zone, so dates are + # compared by the day. None for anything that is not a date. + if isinstance(moment, datetime.datetime): + if moment.tzinfo is not None: + moment = moment.astimezone(datetime.timezone.utc) + return moment.date() + if isinstance(moment, datetime.date): + return moment + return None + + def _is_newer(self, data_file, path): + # Whether the data file at the path was published on a later day + # than the data in use, by the date the engine reads in its header. + # A file is newer when the engine reads no date from it or no date + # is known for the data in use, so it is loaded as it was before + # dates could be read. A header that cannot be read raises a + # DataUpdateException as any other error. + read = self._published_date_reader(data_file) + if read is None: + return True + try: + published = self._published_day(read(path)) + except Exception as e: + raise DataUpdateException( + self._unhandled_message(data_file), + UpdateStatus.AUTO_UPDATE_UNKNOWN_ERROR) from e + if published is None: + return True + in_use = self._published_day_in_use(data_file, read, path) + return in_use is None or published > in_use + + def _published_day_in_use(self, data_file, read, path): + # The day the data in use was published. Before the engine has + # loaded data, as at the update on start-up, it is the day the file + # already at the data file's path was published, which is loaded + # otherwise. None when neither is known, as when there is no file + # there or its header cannot be read. + try: + in_use = self._published_day(data_file.get_date_published()) + except Exception: + in_use = None + if in_use is not None: + return in_use + local = getattr(data_file, "path", None) + if not local or local == path or not os.path.isfile(local): + return None + try: + return self._published_day(read(local)) + except Exception: + return None + + def _is_newer_or_discard(self, data_file, staged): + # Whether the file staged for a download is newer than the data in + # use. A staged file that is not, or whose header cannot be read, is + # deleted, so the data file is left as it was. + try: + newer = self._is_newer(data_file, staged) + except DataUpdateException: + self._discard(staged) + raise + if not newer: + self._discard(staged) + return newer + + @staticmethod + def _discard(path): + # Delete a staged download that is not used. One that cannot be + # deleted is left, as it holds none of the data in use. + try: + os.remove(path) + except OSError: + pass + def _log_failed_check(self, data_file, error): # A check or a watched change that failed is logged with the message # of its row of the errors table and the error that caused it. @@ -989,8 +1102,12 @@ def track_local_data_file_changes(self, data_file): event. It is first opened for reading, waiting up to WATCHED_FILE_WAIT_SECONDS for a copy still being made, and a file that does not open is reported as AUTO_UPDATE_TIMEOUT without a log - entry. Otherwise the refresh takes the same route as the polling one, - so the attempt is logged, a failure carries the errors table's + entry. A file whose engine reads a published date in its header that + is not later than that of the data in use is not loaded, and is + reported as AUTO_UPDATE_NOT_NEEDED without a log entry. A header + that cannot be read is any other error, which is logged and + reported. Otherwise the refresh takes the same route as the polling + one, so the attempt is logged, a failure carries the errors table's message and level, and the result is reported to the update complete callbacks either way. The next check is scheduled whatever happens, so that a later file is still picked up, until the data file is @@ -1028,13 +1145,15 @@ def track_local_data_file_changes(self, data_file): data_file.updating = True try: data_file.last_changed_time = changed_time - if self._wait_until_readable(data_file.path): - self._refresh(data_file) - status = UpdateStatus.AUTO_UPDATE_SUCCESS - else: + if not self._wait_until_readable(data_file.path): # The errors table's row for a watched file that # could not be opened is not logged. status = UpdateStatus.AUTO_UPDATE_TIMEOUT + elif self._is_newer(data_file, data_file.path): + self._refresh(data_file) + status = UpdateStatus.AUTO_UPDATE_SUCCESS + else: + status = UpdateStatus.AUTO_UPDATE_NOT_NEEDED except DataUpdateException as e: self._log_failed_check(data_file, e) status = e.status diff --git a/pipeline/fiftyone_pipeline_engines/tests/test_datafile_published_date.py b/pipeline/fiftyone_pipeline_engines/tests/test_datafile_published_date.py new file mode 100644 index 00000000..f4d2cd13 --- /dev/null +++ b/pipeline/fiftyone_pipeline_engines/tests/test_datafile_published_date.py @@ -0,0 +1,322 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""A watched or downloaded file that is not newer than the data in use is +not loaded, and the check is reported as not needed, as the newFileAvailable +section of the data updates specification says. Whether a file is newer is +decided by the published date the engine reads in the file's header, not by +the file's modification time.""" + +import datetime +import os +import shutil +import tempfile +import time + +from fiftyone_pipeline_engines.datafile_update_service import UpdateStatus + +from .test_datafile_update_http import FileDataFile +from .test_datafile_update_http import UpdateServiceTestCase +from .test_datafile_update_http import response + +# The day the data in use was published. +IN_USE = datetime.date(2026, 11, 3) +ONE_DAY = datetime.timedelta(days=1) + +# A file the engine stands in for reads as this, then its published date. +HEADER = b"published " + +# The message of the errors table's row for any other error. +UNHANDLED = ("An unhandled error occurred while checking for automatic " + "updates for engine 'DatedEngine'") + + +def content(published): + """The content of a data file published on the day given.""" + return HEADER + published.isoformat().encode() + + +class DatedEngine: + """Stands in for an on-premise engine, which reads the published date in + a data file's header. Here the header is the file's content.""" + datakey = "dated" + + def __init__(self): + self.read = [] + + def get_date_published_from_file(self, path): + self.read.append(path) + with open(path, "rb") as file: + header = file.read() + if not header.startswith(HEADER): + raise ValueError("The file is not a data file.") + return datetime.date.fromisoformat(header[len(HEADER):].decode()) + + +class DatedDataFile(FileDataFile): + """A data file kept on disk whose engine reads published dates.""" + + def __init__(self, path): + super(DatedDataFile, self).__init__(path) + self.flow_element = DatedEngine() + self.published = datetime.datetime.combine(IN_USE, datetime.time()) + + +class PublishedDateTestCase(UpdateServiceTestCase): + + def setUp(self): + super(PublishedDateTestCase, self).setUp() + self.make_data_file() + + def make_data_file(self): + """A data file in a folder of its own, whose file holds the data in + use, with nothing reported for it yet.""" + self.folder = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.folder, ignore_errors=True) + self.path = os.path.join(self.folder, "data.dat") + self.old = content(IN_USE) + with open(self.path, "wb") as file: + file.write(self.old) + self.data_file = DatedDataFile(self.path) + self.engine = self.data_file.flow_element + self.statuses.clear() + + def on_disk(self): + with open(self.path, "rb") as file: + return file.read() + + def errors(self): + return [message for level, message in self.pipeline.logs + if level == "error"] + + +# A downloaded file is compared with the data in use before it replaces the +# data file, whether it is written to a temporary copy or beside the data +# file, and one that is not newer is deleted. +class DownloadedFileTests(PublishedDateTestCase): + + def download(self, published, temp_copy): + self.data_file.create_temp_copy = temp_copy + self.temp_folder = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.temp_folder, ignore_errors=True) + self.data_file.temp_directory = self.temp_folder + new = content(published) + self.get(response(200, new)) + self.service.update_data_file(self.data_file) + return new + + def assertNothingLeft(self): + self.assertEqual(["data.dat"], os.listdir(self.folder)) + self.assertEqual([], os.listdir(self.temp_folder)) + + def testALaterFileIsLoaded(self): + for temp_copy in (True, False): + with self.subTest(temp_copy=temp_copy): + self.make_data_file() + new = self.download(IN_USE + ONE_DAY, temp_copy) + self.assertEqual(1, len(self.engine.read)) + self.assertNotEqual(self.path, self.engine.read[0]) + self.assertEqual(new, self.on_disk()) + self.assertEqual([new], self.data_file.refreshed) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + self.assertNothingLeft() + + def testAFileOfTheSameOrAnEarlierDayIsNotLoaded(self): + for published in (IN_USE, IN_USE - ONE_DAY): + for temp_copy in (True, False): + with self.subTest(published=published, temp_copy=temp_copy): + self.make_data_file() + self.download(published, temp_copy) + self.assertEqual(1, len(self.engine.read)) + self.assertEqual(self.old, self.on_disk()) + self.assertEqual([], self.data_file.refreshed) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], + self.statuses) + self.assertEqual([], self.errors()) + self.assertNothingLeft() + + # The check that found nothing newer is followed by the next scheduled + # check, as one that is answered 304 (Not modified) is. + def testTheNextCheckIsScheduled(self): + self.hold_timers() + self.data_file.auto_update = True + self.download(IN_USE, True) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + self.assertEqual(1, len(self.pending)) + + # The If-Modified-Since request is kept, as it saves a download. + def testIfModifiedSinceIsStillSent(self): + self.download(IN_USE, True) + self.assertEqual( + "Tue, 03 Nov 2026 00:00:00 GMT", + self.sent[0]["If-Modified-Since"]) + + # A download whose header cannot be read is not loaded, and is any + # other error. + def testAFileWhoseHeaderCannotBeReadIsAnyOtherError(self): + self.data_file.create_temp_copy = False + self.get(response(200, b"cut")) + self.poll() + self.assertEqual(self.old, self.on_disk()) + self.assertEqual([], self.data_file.refreshed) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_UNKNOWN_ERROR], self.statuses) + self.assertEqual( + [UNHANDLED + ". Error detail: The file is not a data file."], + self.errors()) + self.assertEqual(["data.dat"], os.listdir(self.folder)) + + # Before the engine has loaded data, as at the update on start-up, the + # download is compared with the file already at the data file's path. + def testWithNoDataInUseTheFileOnDiskIsComparedWith(self): + self.data_file.published = AttributeError("engine") + for published, loaded in ( + (IN_USE, False), (IN_USE + ONE_DAY, True)): + with self.subTest(published=published): + self.statuses.clear() + self.data_file.refreshed.clear() + self.download(published, False) + self.assertEqual(loaded, bool(self.data_file.refreshed)) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_SUCCESS if loaded else + UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + + # With no data in use and no file on disk, the download is loaded. + def testWithNoDataInUseAndNoFileTheDownloadIsLoaded(self): + self.data_file.published = AttributeError("engine") + os.remove(self.path) + new = self.download(IN_USE - ONE_DAY, True) + self.assertEqual(new, self.on_disk()) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + + # The header holds a day, so a time on the same day is the same day. + def testDatesAreComparedByTheDay(self): + self.data_file.published = datetime.datetime( + 2026, 11, 3, 23, 59, tzinfo=datetime.timezone.utc) + self.download(IN_USE, True) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + + # A time with a zone is the day it is in UTC. + def testATimeWithAZoneIsTheDayInUtc(self): + self.data_file.published = datetime.datetime( + 2026, 11, 2, 23, 0, + tzinfo=datetime.timezone(-datetime.timedelta(hours=5))) + self.download(IN_USE, True) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + + # Data from memory cannot be compared, so it is loaded. + def testDataKeptInMemoryIsLoadedWithoutComparing(self): + self.data_file.download = False + self.get(response(200, content(IN_USE))) + self.service.update_data_file(self.data_file) + self.assertEqual([], self.engine.read) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + + # An engine that reads no published dates has every download loaded. + def testAnEngineThatReadsNoDatesHasTheDownloadLoaded(self): + self.data_file.flow_element = object() + new = self.download(IN_USE - ONE_DAY, False) + self.assertEqual(new, self.on_disk()) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + + +# A watched file is loaded only when its header gives a later day than the +# data in use, whatever its modification time. +class WatchedFileTests(PublishedDateTestCase): + + def setUp(self): + super(WatchedFileTests, self).setUp() + self.hold_timers() + self.data_file.file_system_watcher = True + self.stamp = time.time() + self.service.register_data_file(self.data_file) + + def replace(self, data): + with open(self.path, "wb") as file: + file.write(data) + # Later than any time the watcher has seen, however coarse the clock. + self.stamp += 10 + os.utime(self.path, (self.stamp, self.stamp)) + + def run_next_check(self): + check = self.pending.pop(0) + check.function(*check.args) + + def testALaterFileIsLoaded(self): + new = content(IN_USE + ONE_DAY) + self.replace(new) + self.run_next_check() + self.assertEqual([self.path], self.engine.read) + self.assertEqual([new], self.data_file.refreshed) + self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + + def testAFileOfTheSameOrAnEarlierDayIsNotLoaded(self): + for published in (IN_USE, IN_USE - ONE_DAY): + with self.subTest(published=published): + self.statuses.clear() + self.engine.read.clear() + self.replace(content(published)) + self.run_next_check() + self.assertEqual([self.path], self.engine.read) + self.assertEqual([], self.data_file.refreshed) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + self.assertEqual([], self.errors()) + self.assertEqual(1, len(self.pending)) + + # The file's time is taken, so it is not checked again. + self.run_next_check() + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + + def testAFileWhoseHeaderCannotBeReadIsAnyOtherError(self): + self.replace(b"cut") + self.run_next_check() + self.assertEqual([], self.data_file.refreshed) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_UNKNOWN_ERROR], self.statuses) + self.assertEqual( + [UNHANDLED + ". Error detail: The file is not a data file."], + self.errors()) + self.assertEqual(1, len(self.pending)) + + # A later good file is still loaded. + new = content(IN_USE + ONE_DAY) + self.replace(new) + self.run_next_check() + self.assertEqual([new], self.data_file.refreshed) + + def testWithNoDataInUseTheWatchedFileIsLoaded(self): + self.data_file.published = AttributeError("engine") + new = content(IN_USE) + self.replace(new) + self.run_next_check() + self.assertEqual([new], self.data_file.refreshed) + self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses)