Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion ddns/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
from tempfile import gettempdir
from time import time

# Windows file timestamps can be slightly ahead of time().
CACHE_MTIME_TOLERANCE_SECONDS = 2


class Cache(dict):
"""
Expand Down Expand Up @@ -175,7 +178,8 @@ def new(config_cache, hash, logger, cache_max_age=259200):
logger.debug("Cache is disabled!")
else:
now = time()
expired = cache.time > now or now - cache.time >= cache_max_age
age = now - min(cache.time, now)
expired = cache.time - now > CACHE_MTIME_TOLERANCE_SECONDS or age >= cache_max_age
if expired:
logger.info("Cache file is outdated.")
cache.clear()
Expand Down
16 changes: 12 additions & 4 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,15 +669,15 @@ def test_cache_new_nonexistent_file(self):

@patch("ddns.cache.time")
def test_cache_new_custom_max_age_and_boundary(self, mock_time):
"""Test custom age, exact expiry boundary, and future mtimes."""
"""Test custom age, exact expiry, and small future file-time skew."""
import json
import logging

with open(self.cache_file, "w") as data:
json.dump({"record": "1.2.3.4"}, data)
logger = logging.getLogger("test_logger")
mock_time.return_value = 1000

with open(self.cache_file, "w") as data:
json.dump({"record": "1.2.3.4"}, data)
with patch("ddns.cache.stat") as mock_stat:
mock_stat.return_value.st_mtime = 900
cache = Cache.new(self.cache_file, "hash", logger, 100)
Expand All @@ -687,7 +687,15 @@ def test_cache_new_custom_max_age_and_boundary(self, mock_time):
with open(self.cache_file, "w") as data:
json.dump({"record": "1.2.3.4"}, data)
with patch("ddns.cache.stat") as mock_stat:
mock_stat.return_value.st_mtime = 1001
mock_stat.return_value.st_mtime = 1002
cache = Cache.new(self.cache_file, "hash", logger, 100)
self.assertEqual(cache.get("record"), "1.2.3.4")
cache.close()

with open(self.cache_file, "w") as data:
json.dump({"record": "1.2.3.4"}, data)
with patch("ddns.cache.stat") as mock_stat:
mock_stat.return_value.st_mtime = 1003
cache = Cache.new(self.cache_file, "hash", logger, 100)
self.assertEqual(len(cache), 0)
cache.close()
Expand Down
Loading