Skip to content

Commit

Permalink
Avoid clearing redis in device rate limiter tests
Browse files Browse the repository at this point in the history
Clearing all of redis masked issues with the caching logic in the
SystemLimit.for_key which isn't good. The right approach is to skip
caching when running in a test.
  • Loading branch information
gherceg committed Feb 19, 2025
1 parent d88a5e7 commit 6221041
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
3 changes: 2 additions & 1 deletion corehq/apps/users/device_rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

DEVICE_LIMIT_PER_USER_KEY = "device_limit_per_user"
DEVICE_LIMIT_PER_USER_DEFAULT = 50
REDIS_KEY_PREFIX = "device-limiter"


class DeviceRateLimiter:
Expand Down Expand Up @@ -78,7 +79,7 @@ def _get_redis_key(self, domain, user_id):
"""
time = datetime.now(timezone.utc)
formatted_time = time.strftime('%Y-%m-%d_%H:%M')
key = f"device-limiter_{domain}_{user_id}_{formatted_time}"
key = f"{REDIS_KEY_PREFIX}_{domain}_{user_id}_{formatted_time}"
return key

def _track_usage(self, redis_key, device_id, is_key_new=False):
Expand Down
8 changes: 5 additions & 3 deletions corehq/apps/users/tests/test_device_rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
from freezegun import freeze_time

from corehq.apps.cloudcare.const import DEVICE_ID as CLOUDCARE_DEVICE_ID
from corehq.apps.users.device_rate_limiter import DEVICE_LIMIT_PER_USER_KEY, device_rate_limiter
from corehq.apps.users.device_rate_limiter import DEVICE_LIMIT_PER_USER_KEY, REDIS_KEY_PREFIX, device_rate_limiter
from corehq.project_limits.models import SystemLimit
from corehq.tests.pytest_plugins.reusedb import clear_redis
from corehq.util.test_utils import flag_disabled, flag_enabled


Expand All @@ -15,7 +14,10 @@ class TestDeviceRateLimiter(TestCase):

def setUp(self):
SystemLimit.objects.create(key=DEVICE_LIMIT_PER_USER_KEY, limit=1)
self.addCleanup(clear_redis)

def tearDown(self):
for key in device_rate_limiter.client.scan_iter(f"{REDIS_KEY_PREFIX}*"):
device_rate_limiter.client.delete(key.decode('utf-8'))

@flag_enabled("DEVICE_RATE_LIMITER")
def test_allowed_if_no_devices_have_been_used_yet(self):
Expand Down

0 comments on commit 6221041

Please sign in to comment.