Skip to content

Commit

Permalink
fix: pass user and shared params when checking for cache keys (#26402) (
Browse files Browse the repository at this point in the history
#26404)

* fix: pass user and shared params when checking for cache keys

* chore(test): added test for user cache in redis_cache

(cherry picked from commit fb2753f)

Co-authored-by: Nikhil Kothari <nik.kothari22@live.com>
  • Loading branch information
mergify[bot] and nikkothari22 committed May 13, 2024
1 parent 94b3936 commit a0eb7c1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
28 changes: 28 additions & 0 deletions frappe/tests/test_caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,34 @@ def calculate_area(radius: float) -> float:
calculate_area(10)
self.assertEqual(function_call_count, 2)

def test_user_cache(self):
function_call_count = 0
PI = 3.1415
ENGINEERING_PI = _E = 3

@redis_cache(user=True)
def calculate_area(radius: float) -> float:
nonlocal function_call_count
PI_APPROX = ENGINEERING_PI if frappe.session.user == "Engineer" else PI
function_call_count += 1
return PI_APPROX * radius**2

with self.set_user("Engineer"):
self.assertEqual(calculate_area(1), ENGINEERING_PI)
self.assertEqual(function_call_count, 1)

with self.set_user("Mathematician"):
self.assertEqual(calculate_area(1), PI)
self.assertEqual(function_call_count, 2)

with self.set_user("Engineer"):
self.assertEqual(calculate_area(1), ENGINEERING_PI)
self.assertEqual(function_call_count, 2)

with self.set_user("Mathematician"):
self.assertEqual(calculate_area(1), PI)
self.assertEqual(function_call_count, 2)


class TestDocumentCache(FrappeAPITestCase):
TEST_DOCTYPE = "User"
Expand Down
3 changes: 2 additions & 1 deletion frappe/utils/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ def redis_cache(ttl: int | None = 3600, user: str | bool | None = None, shared:
args:
ttl: time to expiry in seconds, defaults to 1 hour
user: `true` should cache be specific to session user.
shared: `true` should cache be shared across sites
"""

def wrapper(func: Callable | None = None) -> Callable:
Expand All @@ -150,7 +151,7 @@ def clear_cache():
@wraps(func)
def redis_cache_wrapper(*args, **kwargs):
func_call_key = func_key + "::" + str(__generate_request_cache_key(args, kwargs))
if frappe.cache.exists(func_call_key):
if frappe.cache.exists(func_call_key, user=user, shared=shared):
return frappe.cache.get_value(func_call_key, user=user, shared=shared)
val = func(*args, **kwargs)
ttl = getattr(func, "ttl", 3600)
Expand Down

0 comments on commit a0eb7c1

Please sign in to comment.