Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[1.0.X] Corrected a problem with the database cache backend, and refa…

…ctored the cache test suite to ensure that all the backends are actually tested.

Partial merge of r10031 and r10071 from trunk.


git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.0.X@10086 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit f781205859484ecd5e7af040b5b52f4edaa6d019 1 parent 0abd798
Russell Keith-Magee authored March 18, 2009
1  django/core/cache/backends/db.py
@@ -65,6 +65,7 @@ def _base_set(self, mode, key, value, timeout=None):
65 65
                 cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)])
66 66
         except DatabaseError:
67 67
             # To be threadsafe, updates/inserts are allowed to fail silently
  68
+            transaction.rollback()
68 69
             return False
69 70
         else:
70 71
             transaction.commit_unless_managed()
43  docs/internals/contributing.txt
@@ -184,7 +184,7 @@ Patch style
184 184
       An exception is for code changes that are described more clearly in plain
185 185
       English than in code. Indentation is the most common example; it's hard to
186 186
       read patches when the only difference in code is that it's indented.
187  
-      
  187
+
188 188
       Patches in ``git diff`` format are also acceptable.
189 189
 
190 190
     * When creating patches, always run ``svn diff`` from the top-level
@@ -402,7 +402,7 @@ translated, here's what to do:
402 402
 
403 403
     * Join the `Django i18n mailing list`_ and introduce yourself.
404 404
 
405  
-    * Create translations using the methods described in the 
  405
+    * Create translations using the methods described in the
406 406
       :ref:`i18n documentation <topics-i18n>`. For this you will use the
407 407
       ``django-admin.py makemessages`` tool. In this particular case it should
408 408
       be run from the top-level ``django`` directory of the Django source tree.
@@ -697,9 +697,9 @@ repository:
697 697
       first commit the change to library Y, then commit feature X in a separate
698 698
       commit. This goes a *long way* in helping all core Django developers
699 699
       follow your changes.
700  
-      
701  
-    * Separate bug fixes from feature changes. 
702  
-    
  700
+
  701
+    * Separate bug fixes from feature changes.
  702
+
703 703
       Bug fixes need to be added to the current bugfix branch (e.g. the
704 704
       ``1.0.X`` branch) as well as the current trunk.
705 705
 
@@ -782,6 +782,10 @@ dependencies:
782 782
     *  Textile_
783 783
     *  Docutils_
784 784
     *  setuptools_
  785
+    *  memcached_, plus the either the python-memcached_ or cmemcached_ Python binding
  786
+
  787
+If you want to test the memcached cache backend, you will also need to define
  788
+a :setting:`CACHE_BACKEND` setting that points at your memcached instance.
785 789
 
786 790
 Each of these dependencies is optional. If you're missing any of them, the
787 791
 associated tests will be skipped.
@@ -791,6 +795,9 @@ associated tests will be skipped.
791 795
 .. _Textile: http://pypi.python.org/pypi/textile
792 796
 .. _docutils: http://pypi.python.org/pypi/docutils/0.4
793 797
 .. _setuptools: http://pypi.python.org/pypi/setuptools/
  798
+.. _memcached: http://www.danga.com/memcached/
  799
+.. _python-memcached: http://pypi.python.org/pypi/python-memcached/
  800
+.. _cmemcached: http://pypi.python.org/pypi/cmemcache
794 801
 
795 802
 To run a subset of the unit tests, append the names of the test modules to the
796 803
 ``runtests.py`` command line. See the list of directories in
@@ -862,28 +869,28 @@ for feature branches:
862 869
 
863 870
     1. Feature branches using a distributed revision control system like
864 871
        Git_, Mercurial_, Bazaar_, etc.
865  
-       
866  
-       If you're familiar with one of these tools, this is probably your best 
  872
+
  873
+       If you're familiar with one of these tools, this is probably your best
867 874
        option since it doesn't require any support or buy-in from the Django
868 875
        core developers.
869  
-       
  876
+
870 877
        However, do keep in mind that Django will continue to use Subversion for
871 878
        the foreseeable future, and this will naturally limit the recognition of
872 879
        your branch. Further, if your branch becomes eligible for merging to
873 880
        trunk you'll need to find a core developer familiar with your DVCS of
874 881
        choice who'll actually perform the merge.
875  
-       
  882
+
876 883
        If you do decided to start a distributed branch of Django and choose to make it
877 884
        public, please add the branch to the `Django branches`_ wiki page.
878  
-       
  885
+
879 886
     2. Feature branches using SVN have a higher bar. If you want a branch in SVN
880 887
        itself, you'll need a "mentor" among the :ref:`core committers
881 888
        <internals-committers>`. This person is responsible for actually creating
882 889
        the branch, monitoring your process (see below), and ultimately merging
883 890
        the branch into trunk.
884  
-       
  891
+
885 892
        If you want a feature branch in SVN, you'll need to ask in
886  
-       `django-developers`_ for a mentor. 
  893
+       `django-developers`_ for a mentor.
887 894
 
888 895
 .. _git: http://git.or.cz/
889 896
 .. _mercurial: http://www.selenic.com/mercurial/
@@ -894,7 +901,7 @@ Branch rules
894 901
 ------------
895 902
 
896 903
 We've got a few rules for branches born out of experience with what makes a
897  
-successful Django branch. 
  904
+successful Django branch.
898 905
 
899 906
 DVCS branches are obviously not under central control, so we have no way of
900 907
 enforcing these rules. However, if you're using a DVCS, following these rules
@@ -908,19 +915,19 @@ rules are broken.
908 915
     * Only branch entire copies of the Django tree, even if work is only
909 916
       happening on part of that tree. This makes it painless to switch to a
910 917
       branch.
911  
-      
  918
+
912 919
     * Merge changes from trunk no less than once a week, and preferably every
913 920
       couple-three days.
914  
-      
  921
+
915 922
       In our experience, doing regular trunk merges is often the difference
916 923
       between a successful branch and one that fizzles and dies.
917  
-      
  924
+
918 925
       If you're working on an SVN branch, you should be using `svnmerge.py`_
919 926
       to track merges from trunk.
920  
-      
  927
+
921 928
     * Keep tests passing and documentation up-to-date. As with patches,
922 929
       we'll only merge a branch that comes with tests and documentation.
923  
-      
  930
+
924 931
 .. _svnmerge.py: http://www.orcaware.com/svn/wiki/Svnmerge.py
925 932
 
926 933
 Once the branch is stable and ready to be merged into the trunk, alert
154  tests/regressiontests/cache/tests.py
@@ -9,8 +9,10 @@
9 9
 import time
10 10
 import unittest
11 11
 
12  
-from django.core.cache import cache, get_cache
13  
-from django.core.cache.backends.filebased import CacheClass as FileCache
  12
+from django.conf import settings
  13
+from django.core import management
  14
+from django.core.cache import get_cache
  15
+from django.core.cache.backends.base import InvalidCacheBackendError
14 16
 from django.http import HttpResponse
15 17
 from django.utils.cache import patch_vary_headers
16 18
 from django.utils.hashcompat import md5_constructor
@@ -22,39 +24,121 @@ class C:
22 24
     def m(n):
23 25
         return 24
24 26
 
25  
-class Cache(unittest.TestCase):
  27
+class DummyCacheTests(unittest.TestCase):
  28
+    # The Dummy cache backend doesn't really behave like a test backend,
  29
+    # so it has different test requirements.
26 30
     def setUp(self):
27  
-        # Special-case the file cache so we can clean up after ourselves.
28  
-        if isinstance(cache, FileCache):
29  
-            self.cache_dir = tempfile.mkdtemp()
30  
-            self.cache = get_cache("file:///%s" % self.cache_dir)
31  
-        else:
32  
-            self.cache_dir = None
33  
-            self.cache = cache
34  
-            
35  
-    def tearDown(self):
36  
-        if self.cache_dir is not None:
37  
-            shutil.rmtree(self.cache_dir)
38  
-    
  31
+        self.cache = get_cache('dummy://')
  32
+
  33
+    def test_simple(self):
  34
+        "Dummy cache backend ignores cache set calls"
  35
+        self.cache.set("key", "value")
  36
+        self.assertEqual(self.cache.get("key"), None)
  37
+
  38
+    def test_add(self):
  39
+        "Add doesn't do anything in dummy cache backend"
  40
+        self.cache.add("addkey1", "value")
  41
+        result = self.cache.add("addkey1", "newvalue")
  42
+        self.assertEqual(result, True)
  43
+        self.assertEqual(self.cache.get("addkey1"), None)
  44
+
  45
+    def test_non_existent(self):
  46
+        "Non-existent keys aren't found in the dummy cache backend"
  47
+        self.assertEqual(self.cache.get("does_not_exist"), None)
  48
+        self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  49
+
  50
+    def test_get_many(self):
  51
+        "get_many returns nothing for the dummy cache backend"
  52
+        self.cache.set('a', 'a')
  53
+        self.cache.set('b', 'b')
  54
+        self.cache.set('c', 'c')
  55
+        self.cache.set('d', 'd')
  56
+        self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {})
  57
+        self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {})
  58
+
  59
+    def test_delete(self):
  60
+        "Cache deletion is transparently ignored on the dummy cache backend"
  61
+        self.cache.set("key1", "spam")
  62
+        self.cache.set("key2", "eggs")
  63
+        self.assertEqual(self.cache.get("key1"), None)
  64
+        self.cache.delete("key1")
  65
+        self.assertEqual(self.cache.get("key1"), None)
  66
+        self.assertEqual(self.cache.get("key2"), None)
  67
+
  68
+    def test_has_key(self):
  69
+        "The has_key method doesn't ever return True for the dummy cache backend"
  70
+        self.cache.set("hello1", "goodbye1")
  71
+        self.assertEqual(self.cache.has_key("hello1"), False)
  72
+        self.assertEqual(self.cache.has_key("goodbye1"), False)
  73
+
  74
+    def test_in(self):
  75
+        "The in operator doesn't ever return True for the dummy cache backend"
  76
+        self.cache.set("hello2", "goodbye2")
  77
+        self.assertEqual("hello2" in self.cache, False)
  78
+        self.assertEqual("goodbye2" in self.cache, False)
  79
+
  80
+    def test_data_types(self):
  81
+        "All data types are ignored equally by the dummy cache"
  82
+        stuff = {
  83
+            'string'    : 'this is a string',
  84
+            'int'       : 42,
  85
+            'list'      : [1, 2, 3, 4],
  86
+            'tuple'     : (1, 2, 3, 4),
  87
+            'dict'      : {'A': 1, 'B' : 2},
  88
+            'function'  : f,
  89
+            'class'     : C,
  90
+        }
  91
+        self.cache.set("stuff", stuff)
  92
+        self.assertEqual(self.cache.get("stuff"), None)
  93
+
  94
+    def test_expiration(self):
  95
+        "Expiration has no effect on the dummy cache"
  96
+        self.cache.set('expire1', 'very quickly', 1)
  97
+        self.cache.set('expire2', 'very quickly', 1)
  98
+        self.cache.set('expire3', 'very quickly', 1)
  99
+
  100
+        time.sleep(2)
  101
+        self.assertEqual(self.cache.get("expire1"), None)
  102
+
  103
+        self.cache.add("expire2", "newvalue")
  104
+        self.assertEqual(self.cache.get("expire2"), None)
  105
+        self.assertEqual(self.cache.has_key("expire3"), False)
  106
+
  107
+    def test_unicode(self):
  108
+        "Unicode values are ignored by the dummy cache"
  109
+        stuff = {
  110
+            u'ascii': u'ascii_value',
  111
+            u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
  112
+            u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2',
  113
+            u'ascii': {u'x' : 1 }
  114
+            }
  115
+        for (key, value) in stuff.items():
  116
+            self.cache.set(key, value)
  117
+            self.assertEqual(self.cache.get(key), None)
  118
+
  119
+
  120
+class BaseCacheTests(object):
  121
+    # A common set of tests to apply to all cache backends
39 122
     def test_simple(self):
40  
-        # simple set/get
  123
+        # Simple cache set/get works
41 124
         self.cache.set("key", "value")
42 125
         self.assertEqual(self.cache.get("key"), "value")
43 126
 
44 127
     def test_add(self):
45  
-        # test add (only add if key isn't already in cache)
  128
+        # A key can be added to a cache
46 129
         self.cache.add("addkey1", "value")
47 130
         result = self.cache.add("addkey1", "newvalue")
48 131
         self.assertEqual(result, False)
49 132
         self.assertEqual(self.cache.get("addkey1"), "value")
50 133
 
51 134
     def test_non_existent(self):
  135
+        # Non-existent cache keys return as None/default
52 136
         # get with non-existent keys
53 137
         self.assertEqual(self.cache.get("does_not_exist"), None)
54 138
         self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
55 139
 
56 140
     def test_get_many(self):
57  
-        # get_many
  141
+        # Multiple cache keys can be returned using get_many
58 142
         self.cache.set('a', 'a')
59 143
         self.cache.set('b', 'b')
60 144
         self.cache.set('c', 'c')
@@ -63,7 +147,7 @@ def test_get_many(self):
63 147
         self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
64 148
 
65 149
     def test_delete(self):
66  
-        # delete
  150
+        # Cache keys can be deleted
67 151
         self.cache.set("key1", "spam")
68 152
         self.cache.set("key2", "eggs")
69 153
         self.assertEqual(self.cache.get("key1"), "spam")
@@ -72,17 +156,19 @@ def test_delete(self):
72 156
         self.assertEqual(self.cache.get("key2"), "eggs")
73 157
 
74 158
     def test_has_key(self):
75  
-        # has_key
  159
+        # The cache can be inspected for cache keys
76 160
         self.cache.set("hello1", "goodbye1")
77 161
         self.assertEqual(self.cache.has_key("hello1"), True)
78 162
         self.assertEqual(self.cache.has_key("goodbye1"), False)
79 163
 
80 164
     def test_in(self):
  165
+        # The in operator can be used to inspet cache contents
81 166
         self.cache.set("hello2", "goodbye2")
82 167
         self.assertEqual("hello2" in self.cache, True)
83 168
         self.assertEqual("goodbye2" in self.cache, False)
84 169
 
85 170
     def test_data_types(self):
  171
+        # Many different data types can be cached
86 172
         stuff = {
87 173
             'string'    : 'this is a string',
88 174
             'int'       : 42,
@@ -96,6 +182,7 @@ def test_data_types(self):
96 182
         self.assertEqual(self.cache.get("stuff"), stuff)
97 183
 
98 184
     def test_expiration(self):
  185
+        # Cache values can be set to expire
99 186
         self.cache.set('expire1', 'very quickly', 1)
100 187
         self.cache.set('expire2', 'very quickly', 1)
101 188
         self.cache.set('expire3', 'very quickly', 1)
@@ -108,6 +195,7 @@ def test_expiration(self):
108 195
         self.assertEqual(self.cache.has_key("expire3"), False)
109 196
 
110 197
     def test_unicode(self):
  198
+        # Unicode values can be cached
111 199
         stuff = {
112 200
             u'ascii': u'ascii_value',
113 201
             u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
@@ -118,14 +206,36 @@ def test_unicode(self):
118 206
             self.cache.set(key, value)
119 207
             self.assertEqual(self.cache.get(key), value)
120 208
 
  209
+class DBCacheTests(unittest.TestCase, BaseCacheTests):
  210
+    def setUp(self):
  211
+        management.call_command('createcachetable', 'test_cache_table', verbosity=0, interactive=False)
  212
+        self.cache = get_cache('db://test_cache_table')
  213
+
  214
+    def tearDown(self):
  215
+        from django.db import connection
  216
+        cursor = connection.cursor()
  217
+        cursor.execute('DROP TABLE test_cache_table');
  218
+
  219
+class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
  220
+    def setUp(self):
  221
+        self.cache = get_cache('locmem://')
  222
+
  223
+# memcached backend isn't guaranteed to be available.
  224
+# To check the memcached backend, the test settings file will
  225
+# need to contain a CACHE_BACKEND setting that points at
  226
+# your memcache server.
  227
+if settings.CACHE_BACKEND.startswith('memcached://'):
  228
+    class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
  229
+        def setUp(self):
  230
+            self.cache = get_cache(settings.CACHE_BACKEND)
121 231
 
122  
-class FileBasedCacheTests(unittest.TestCase):
  232
+class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
123 233
     """
124 234
     Specific test cases for the file-based cache.
125 235
     """
126 236
     def setUp(self):
127 237
         self.dirname = tempfile.mkdtemp()
128  
-        self.cache = FileCache(self.dirname, {})
  238
+        self.cache = get_cache('file://%s' % self.dirname)
129 239
 
130 240
     def tearDown(self):
131 241
         shutil.rmtree(self.dirname)

0 notes on commit f781205

Please sign in to comment.
Something went wrong with that request. Please try again.