| 1 |
from cachalot.transaction import AtomicCache |
| 2 |
|
| 3 |
from django.contrib.auth.models import User |
| 4 |
from django.core.cache import cache |
| 5 |
from django.db import transaction, connection, IntegrityError |
| 6 |
from django.test import SimpleTestCase, skipUnlessDBFeature |
| 7 |
|
| 8 |
from .models import Test |
| 9 |
from .test_utils import TestUtilsMixin, FilteredTransactionTestCase |
| 10 |
|
| 11 |
|
| 12 |
class AtomicTestCase(TestUtilsMixin, FilteredTransactionTestCase): |
| 13 |
def test_successful_read_atomic(self): |
| 14 |
with self.assertNumQueries(1): |
| 15 |
with transaction.atomic(): |
| 16 |
data1 = list(Test.objects.all()) |
| 17 |
self.assertListEqual(data1, []) |
| 18 |
|
| 19 |
with self.assertNumQueries(0): |
| 20 |
data2 = list(Test.objects.all()) |
| 21 |
self.assertListEqual(data2, []) |
| 22 |
|
| 23 |
def test_unsuccessful_read_atomic(self): |
| 24 |
with self.assertNumQueries(1): |
| 25 |
try: |
| 26 |
with transaction.atomic(): |
| 27 |
data1 = list(Test.objects.all()) |
| 28 |
raise ZeroDivisionError |
| 29 |
except ZeroDivisionError: |
| 30 |
pass |
| 31 |
self.assertListEqual(data1, []) |
| 32 |
|
| 33 |
with self.assertNumQueries(1): |
| 34 |
data2 = list(Test.objects.all()) |
| 35 |
self.assertListEqual(data2, []) |
| 36 |
|
| 37 |
def test_successful_write_atomic(self): |
| 38 |
with self.assertNumQueries(1): |
| 39 |
data1 = list(Test.objects.all()) |
| 40 |
self.assertListEqual(data1, []) |
| 41 |
|
| 42 |
with self.assertNumQueries(1): |
| 43 |
with transaction.atomic(): |
| 44 |
t1 = Test.objects.create(name='test1') |
| 45 |
with self.assertNumQueries(1): |
| 46 |
data2 = list(Test.objects.all()) |
| 47 |
self.assertListEqual(data2, [t1]) |
| 48 |
|
| 49 |
with self.assertNumQueries(1): |
| 50 |
with transaction.atomic(): |
| 51 |
t2 = Test.objects.create(name='test2') |
| 52 |
with self.assertNumQueries(1): |
| 53 |
data3 = list(Test.objects.all()) |
| 54 |
self.assertListEqual(data3, [t1, t2]) |
| 55 |
|
| 56 |
with self.assertNumQueries(3): |
| 57 |
with transaction.atomic(): |
| 58 |
data4 = list(Test.objects.all()) |
| 59 |
t3 = Test.objects.create(name='test3') |
| 60 |
t4 = Test.objects.create(name='test4') |
| 61 |
data5 = list(Test.objects.all()) |
| 62 |
self.assertListEqual(data4, [t1, t2]) |
| 63 |
self.assertListEqual(data5, [t1, t2, t3, t4]) |
| 64 |
self.assertNotEqual(t4, t3) |
| 65 |
|
| 66 |
def test_unsuccessful_write_atomic(self): |
| 67 |
with self.assertNumQueries(1): |
| 68 |
data1 = list(Test.objects.all()) |
| 69 |
self.assertListEqual(data1, []) |
| 70 |
|
| 71 |
with self.assertNumQueries(1): |
| 72 |
try: |
| 73 |
with transaction.atomic(): |
| 74 |
Test.objects.create(name='test') |
| 75 |
raise ZeroDivisionError |
| 76 |
except ZeroDivisionError: |
| 77 |
pass |
| 78 |
with self.assertNumQueries(0): |
| 79 |
data2 = list(Test.objects.all()) |
| 80 |
self.assertListEqual(data2, []) |
| 81 |
with self.assertNumQueries(1): |
| 82 |
with self.assertRaises(Test.DoesNotExist): |
| 83 |
Test.objects.get(name='test') |
| 84 |
|
| 85 |
def test_cache_inside_atomic(self): |
| 86 |
with self.assertNumQueries(1): |
| 87 |
with transaction.atomic(): |
| 88 |
data1 = list(Test.objects.all()) |
| 89 |
data2 = list(Test.objects.all()) |
| 90 |
self.assertListEqual(data2, data1) |
| 91 |
self.assertListEqual(data2, []) |
| 92 |
|
| 93 |
def test_invalidation_inside_atomic(self): |
| 94 |
with self.assertNumQueries(3): |
| 95 |
with transaction.atomic(): |
| 96 |
data1 = list(Test.objects.all()) |
| 97 |
t = Test.objects.create(name='test') |
| 98 |
data2 = list(Test.objects.all()) |
| 99 |
self.assertListEqual(data1, []) |
| 100 |
self.assertListEqual(data2, [t]) |
| 101 |
|
| 102 |
def test_successful_nested_read_atomic(self): |
| 103 |
with self.assertNumQueries(6): |
| 104 |
with transaction.atomic(): |
| 105 |
list(Test.objects.all()) |
| 106 |
with transaction.atomic(): |
| 107 |
list(User.objects.all()) |
| 108 |
with self.assertNumQueries(2): |
| 109 |
with transaction.atomic(): |
| 110 |
list(User.objects.all()) |
| 111 |
with self.assertNumQueries(0): |
| 112 |
list(User.objects.all()) |
| 113 |
with self.assertNumQueries(0): |
| 114 |
list(Test.objects.all()) |
| 115 |
list(User.objects.all()) |
| 116 |
|
| 117 |
def test_unsuccessful_nested_read_atomic(self): |
| 118 |
with self.assertNumQueries(5): |
| 119 |
with transaction.atomic(): |
| 120 |
try: |
| 121 |
with transaction.atomic(): |
| 122 |
with self.assertNumQueries(1): |
| 123 |
list(Test.objects.all()) |
| 124 |
raise ZeroDivisionError |
| 125 |
except ZeroDivisionError: |
| 126 |
pass |
| 127 |
with self.assertNumQueries(1): |
| 128 |
list(Test.objects.all()) |
| 129 |
|
| 130 |
def test_successful_nested_write_atomic(self): |
| 131 |
with self.assertNumQueries(12): |
| 132 |
with transaction.atomic(): |
| 133 |
t1 = Test.objects.create(name='test1') |
| 134 |
with transaction.atomic(): |
| 135 |
t2 = Test.objects.create(name='test2') |
| 136 |
data1 = list(Test.objects.all()) |
| 137 |
self.assertListEqual(data1, [t1, t2]) |
| 138 |
with transaction.atomic(): |
| 139 |
t3 = Test.objects.create(name='test3') |
| 140 |
with transaction.atomic(): |
| 141 |
data2 = list(Test.objects.all()) |
| 142 |
self.assertListEqual(data2, [t1, t2, t3]) |
| 143 |
t4 = Test.objects.create(name='test4') |
| 144 |
data3 = list(Test.objects.all()) |
| 145 |
self.assertListEqual(data3, [t1, t2, t3, t4]) |
| 146 |
|
| 147 |
def test_unsuccessful_nested_write_atomic(self): |
| 148 |
with self.assertNumQueries(15): |
| 149 |
with transaction.atomic(): |
| 150 |
t1 = Test.objects.create(name='test1') |
| 151 |
try: |
| 152 |
with transaction.atomic(): |
| 153 |
t2 = Test.objects.create(name='test2') |
| 154 |
data1 = list(Test.objects.all()) |
| 155 |
self.assertListEqual(data1, [t1, t2]) |
| 156 |
raise ZeroDivisionError |
| 157 |
except ZeroDivisionError: |
| 158 |
pass |
| 159 |
data2 = list(Test.objects.all()) |
| 160 |
self.assertListEqual(data2, [t1]) |
| 161 |
try: |
| 162 |
with transaction.atomic(): |
| 163 |
t3 = Test.objects.create(name='test3') |
| 164 |
with transaction.atomic(): |
| 165 |
data2 = list(Test.objects.all()) |
| 166 |
self.assertListEqual(data2, [t1, t3]) |
| 167 |
raise ZeroDivisionError |
| 168 |
except ZeroDivisionError: |
| 169 |
pass |
| 170 |
with self.assertNumQueries(1): |
| 171 |
data3 = list(Test.objects.all()) |
| 172 |
self.assertListEqual(data3, [t1]) |
| 173 |
|
| 174 |
@skipUnlessDBFeature('can_defer_constraint_checks') |
| 175 |
def test_deferred_error(self): |
| 176 |
""" |
| 177 |
Checks that an error occurring during the end of a transaction |
| 178 |
has no impact on future queries. |
| 179 |
""" |
| 180 |
with connection.cursor() as cursor: |
| 181 |
cursor.execute( |
| 182 |
'CREATE TABLE example (' |
| 183 |
'id int UNIQUE DEFERRABLE INITIALLY DEFERRED);') |
| 184 |
with self.assertRaises(IntegrityError): |
| 185 |
with transaction.atomic(): |
| 186 |
with self.assertNumQueries(1): |
| 187 |
list(Test.objects.all()) |
| 188 |
cursor.execute( |
| 189 |
'INSERT INTO example VALUES (1), (1);' |
| 190 |
'-- ' + Test._meta.db_table) # Should invalidate Test. |
| 191 |
with self.assertNumQueries(1): |
| 192 |
list(Test.objects.all()) |
| 193 |
|
| 194 |
|
| 195 |
class AtomicCacheTestCase(SimpleTestCase): |
| 196 |
def setUp(self): |
| 197 |
self.atomic_cache = AtomicCache(cache, 'db_alias') |
| 198 |
|
| 199 |
def test_set(self): |
| 200 |
self.assertDictEqual(self.atomic_cache, {}) |
| 201 |
self.atomic_cache.set('key', 'value', None) |
| 202 |
self.assertDictEqual(self.atomic_cache, {'key': 'value'}) |
| 203 |
|
| 204 |
def test_get_many(self): |
| 205 |
"""Test basic get_many functionality""" |
| 206 |
# Setup mock parent cache |
| 207 |
class MockCache: |
| 208 |
def __init__(self): |
| 209 |
self.data = {} |
| 210 |
|
| 211 |
def get_many(self, keys): |
| 212 |
return {k: self.data[k] for k in keys if k in self.data} |
| 213 |
|
| 214 |
def set(self, key, value, timeout=None): |
| 215 |
self.data[key] = value |
| 216 |
|
| 217 |
parent_cache = MockCache() |
| 218 |
parent_cache.set('parent_key', 'parent_value') |
| 219 |
|
| 220 |
# Setup atomic cache with values |
| 221 |
atomic_cache = AtomicCache(parent_cache, 'db_alias') |
| 222 |
atomic_cache.set('local_key', 'local_value', None) |
| 223 |
|
| 224 |
# Test get_many retrieves from both caches |
| 225 |
result = atomic_cache.get_many(['local_key', 'parent_key', 'missing_key']) |
| 226 |
|
| 227 |
self.assertEqual(result['local_key'], 'local_value') |
| 228 |
self.assertEqual(result['parent_key'], 'parent_value') |
| 229 |
self.assertNotIn('missing_key', result) |
| 230 |
|
| 231 |
def test_nested_atomic_caches(self): |
| 232 |
""" |
| 233 |
Test that nested AtomicCache instances don't cause recursion errors. |
| 234 |
This simulates the scenario that was causing the RecursionError in issue #262. |
| 235 |
""" |
| 236 |
# Create a base cache |
| 237 |
class MockBaseCache: |
| 238 |
def __init__(self): |
| 239 |
self.data = {} |
| 240 |
|
| 241 |
def get_many(self, keys): |
| 242 |
result = {} |
| 243 |
for k in keys: |
| 244 |
result[k] = self.data.get(k, f'base_value_{k}') |
| 245 |
return result |
| 246 |
|
| 247 |
def set(self, key, value, timeout=None): |
| 248 |
self.data[key] = value |
| 249 |
|
| 250 |
base_cache = MockBaseCache() |
| 251 |
|
| 252 |
# Create a nested chain of AtomicCache instances (simulating middleware wrapping) |
| 253 |
cache_level_1 = AtomicCache(base_cache, 'db1') |
| 254 |
cache_level_2 = AtomicCache(cache_level_1, 'db2') |
| 255 |
cache_level_3 = AtomicCache(cache_level_2, 'db3') |
| 256 |
|
| 257 |
# Set some values at different levels |
| 258 |
cache_level_1.set('key1', 'value1', None) |
| 259 |
cache_level_2.set('key2', 'value2', None) |
| 260 |
|
| 261 |
# Test get_many traverses the chain without recursion |
| 262 |
result = cache_level_3.get_many(['key1', 'key2', 'key3']) |
| 263 |
|
| 264 |
# Verify results - key1 from level_1, key2 from level_2, key3 from base |
| 265 |
self.assertEqual(result['key1'], 'value1') |
| 266 |
self.assertEqual(result['key2'], 'value2') |
| 267 |
self.assertEqual(result['key3'], 'base_value_key3') |
| 268 |
|
| 269 |
def test_circular_reference(self): |
| 270 |
""" |
| 271 |
Test that AtomicCache handles circular references correctly. |
| 272 |
This verifies that the fix prevents infinite recursion with cyclic cache chains. |
| 273 |
""" |
| 274 |
# Create a mock base cache |
| 275 |
class MockBaseCache: |
| 276 |
def __init__(self): |
| 277 |
self.data = {} |
| 278 |
|
| 279 |
def get_many(self, keys): |
| 280 |
return {k: self.data.get(k, f'base_value_{k}') for k in keys} |
| 281 |
|
| 282 |
def set(self, key, value, timeout=None): |
| 283 |
self.data[key] = value |
| 284 |
|
| 285 |
base_cache = MockBaseCache() |
| 286 |
|
| 287 |
# Create atomic caches |
| 288 |
cache1 = AtomicCache(base_cache, 'db1') |
| 289 |
cache2 = AtomicCache(cache1, 'db2') |
| 290 |
|
| 291 |
# Create a circular reference (would cause recursion without the fix) |
| 292 |
cache1.parent_cache = cache2 |
| 293 |
|
| 294 |
# Add some values |
| 295 |
cache1.set('key1', 'value1', None) |
| 296 |
cache2.set('key2', 'value2', None) |
| 297 |
|
| 298 |
# This should not cause infinite recursion |
| 299 |
result = cache2.get_many(['key1', 'key2', 'key3']) |
| 300 |
|
| 301 |
# We should get the values from the dictionaries directly |
| 302 |
self.assertEqual(result['key1'], 'value1') |
| 303 |
self.assertEqual(result['key2'], 'value2') |
| 304 |
# key3 is not in the result because the circular reference prevents reaching base_cache |
| 305 |
self.assertNotIn('key3', result) |
| 306 |
|
| 307 |
def test_debug_toolbar_scenario(self): |
| 308 |
""" |
| 309 |
Simulate the Django Debug Toolbar scenario that triggered the original issue. |
| 310 |
Tests that the fix handles nested middleware caches correctly. |
| 311 |
""" |
| 312 |
# Create a mock for the underlying Django Redis cache |
| 313 |
class MockRedisCache: |
| 314 |
def __init__(self): |
| 315 |
self.data = {} |
| 316 |
|
| 317 |
def get_many(self, keys): |
| 318 |
result = {} |
| 319 |
for k in keys: |
| 320 |
result[k] = self.data.get(k, f'redis_value_{k}') |
| 321 |
return result |
| 322 |
|
| 323 |
def set(self, key, value, timeout=None): |
| 324 |
self.data[key] = value |
| 325 |
|
| 326 |
redis_cache = MockRedisCache() |
| 327 |
|
| 328 |
# Create a nested chain of AtomicCache instances |
| 329 |
django_cache = AtomicCache(redis_cache, 'default') |
| 330 |
debug_toolbar_cache = AtomicCache(django_cache, 'default') # Debug Toolbar wraps |
| 331 |
silk_cache = AtomicCache(debug_toolbar_cache, 'default') # Silk wraps |
| 332 |
|
| 333 |
# Add some values to different levels |
| 334 |
django_cache.set('django_key', 'django_value', None) |
| 335 |
debug_toolbar_cache.set('toolbar_key', 'toolbar_value', None) |
| 336 |
silk_cache.set('silk_key', 'silk_value', None) |
| 337 |
|
| 338 |
# Create a large set of keys to test |
| 339 |
test_keys = ['django_key', 'toolbar_key', 'silk_key'] + [f'key{i}' for i in range(1000)] |
| 340 |
|
| 341 |
# This should not cause recursion errors |
| 342 |
result = silk_cache.get_many(test_keys) |
| 343 |
|
| 344 |
# Verify that we got the expected values |
| 345 |
self.assertEqual(result['django_key'], 'django_value') |
| 346 |
self.assertEqual(result['toolbar_key'], 'toolbar_value') |
| 347 |
self.assertEqual(result['silk_key'], 'silk_value') |
| 348 |
|
| 349 |
# Verify that the remaining keys were fetched from the redis cache |
| 350 |
for i in range(10): |
| 351 |
key = f'key{i}' |
| 352 |
self.assertEqual(result[key], f'redis_value_{key}') |