diff options
author | Thomas Kemmer <tkemmer@computer.org> | 2021-09-29 21:51:02 +0200 |
---|---|---|
committer | Thomas Kemmer <tkemmer@computer.org> | 2021-09-29 22:10:55 +0200 |
commit | c0162c5163b498dc31995f88147b868872ae20d4 (patch) | |
tree | 9d42bdab322a255a71be822ae423f5d0511fe13b | |
parent | 7ae6ef5749db9138a555edf58d6b01b6778cf6ad (diff) | |
download | cachetools-c0162c5163b498dc31995f88147b868872ae20d4.tar.gz |
Fix #216: Add documentation and tests for using TTLCache with datetime.
-rw-r--r-- | docs/index.rst | 14 | ||||
-rw-r--r-- | tests/test_ttl.py | 12 |
2 files changed, 24 insertions, 2 deletions
diff --git a/docs/index.rst b/docs/index.rst index 147a19f..c9828b3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -26,7 +26,7 @@ calls are provided, too. .. testsetup:: * import operator - from cachetools import cached, cachedmethod, LRUCache + from cachetools import cached, cachedmethod, LRUCache, TTLCache from unittest import mock urllib = mock.MagicMock() @@ -122,7 +122,17 @@ computed when the item is inserted into the cache. By default, the time-to-live is specified in seconds and :func:`time.monotonic` is used to retrieve the current time. A - custom `timer` function can be supplied if needed. + custom `timer` function can also be supplied: + + .. testcode:: + + from datetime import datetime, timedelta + + cache = TTLCache(maxsize=10, ttl=timedelta(hours=12), timer=datetime.now) + + The expression `timer() + ttl` at the time of insertion defines the + expiration time of a cache item, and must be comparable against + later results of `timer()`. .. method:: expire(self, time=None) diff --git a/tests/test_ttl.py b/tests/test_ttl.py index f677c9b..6e51a59 100644 --- a/tests/test_ttl.py +++ b/tests/test_ttl.py @@ -182,3 +182,15 @@ class TTLCacheTest(unittest.TestCase, CacheTestMixin): with self.assertRaises(KeyError): cache[(1, 2, 3)] self.assertNotIn((1, 2, 3), cache) + + def test_ttl_datetime(self): + from datetime import datetime, timedelta + + cache = TTLCache(maxsize=1, ttl=timedelta(days=1), timer=datetime.now) + + cache[1] = 1 + self.assertEqual(1, len(cache)) + cache.expire(datetime.now()) + self.assertEqual(1, len(cache)) + cache.expire(datetime.now() + timedelta(days=1)) + self.assertEqual(0, len(cache)) |