Commits

Thomas Waldmann  committed 3924f84

fix FileSystemCache._prune issues, see below

fixed confusion of cache keys with fs cache filenames
added 'rb' file opening mode
made sure the file gets closed in all cases (this is especially important
for some platforms if we want to remove that file)

added a test for the _prune code

  • Participants
  • Parent commits 33fd0c0

Comments (0)

Files changed (2)

File tests/contrib/test_cache.py

-from werkzeug.contrib.cache import SimpleCache
+import os, tempfile, shutil
+
+from werkzeug.contrib.cache import SimpleCache, FileSystemCache
 
 
 def test_simplecache_get_dict():
     assert 'a' == d['a']
     assert 'b' in d
     assert 'b' == d['b']
+
+
+def test_filesystemcache_prune():
+    """
+    test if FileSystemCache._prune works and keeps the cache entry count
+    below the given threshold.
+    """
+    THRESHOLD = 13
+    tmp_dir = tempfile.mkdtemp()
+    cache = FileSystemCache(cache_dir=tmp_dir, threshold=THRESHOLD)
+    for i in range(2 * THRESHOLD):
+        cache.set(str(i), i)
+    cache_files = os.listdir(tmp_dir)
+    shutil.rmtree(tmp_dir)
+    assert len(cache_files) <= THRESHOLD
+

File werkzeug/contrib/cache.py

         entries = os.listdir(self._path)
         if len(entries) > self._threshold:
             now = time()
-            for idx, key in enumerate(entries):
+            for idx, fname in enumerate(entries):
+                remove = False
+                fname = os.path.join(self._path, fname)
+                f = None
                 try:
-                    f = file(self._get_filename(key))
-                    if load(f) > now and idx % 3 != 0:
-                        f.close()
-                        continue
+                    try:
+                        f = file(fname, 'rb')
+                        expires = load(f)
+                        remove = expires <= now or idx % 3 == 0
+                    finally:
+                        if f is not None:
+                            f.close()
                 except:
-                    f.close()
-                self.delete(key)
+                    pass
+                if remove:
+                    try:
+                        os.remove(fname)
+                    except (IOError, OSError):
+                        pass
 
     def _get_filename(self, key):
         hash = md5(key).hexdigest()