def test_redis_reset(self): storage = RedisStorage("redis://localhost:6379") limiter = FixedWindowRateLimiter(storage) for i in range(0, 10000): rate = RateLimitItemPerMinute(i) limiter.hit(rate) self.assertEqual(storage.reset(), 10000)
class RedisStorageTests(unittest.TestCase): def setUp(self): self.storage_url = "redis://localhost:6379" self.storage = RedisStorage(self.storage_url) redis.Redis().flushall() def test_redis(self): limiter = FixedWindowRateLimiter(self.storage) per_second = RateLimitItemPerSecond(10) start = time.time() count = 0 while time.time() - start < 0.5 and count < 10: self.assertTrue(limiter.hit(per_second)) count += 1 self.assertFalse(limiter.hit(per_second)) while time.time() - start <= 1: time.sleep(0.1) self.assertTrue(limiter.hit(per_second)) def test_redis_options(self): with mock.patch("limits.storage.get_dependency") as get_dependency: storage_from_string(self.storage_url, connection_timeout=1) self.assertEqual( get_dependency().from_url.call_args[1]['connection_timeout'], 1) def test_redis_reset(self): limiter = FixedWindowRateLimiter(self.storage) for i in range(0, 100): rate = RateLimitItemPerMinute(i) limiter.hit(rate) self.assertEqual(self.storage.reset(), 100) def test_redis_fixed_window_clear(self): limiter = FixedWindowRateLimiter(self.storage) per_min = RateLimitItemPerMinute(1) limiter.hit(per_min) self.assertFalse(limiter.hit(per_min)) limiter.clear(per_min) self.assertTrue(limiter.hit(per_min)) def test_redis_moving_window_clear(self): limiter = MovingWindowRateLimiter(self.storage) per_min = RateLimitItemPerMinute(1) limiter.hit(per_min) self.assertFalse(limiter.hit(per_min)) limiter.clear(per_min) self.assertTrue(limiter.hit(per_min)) def test_large_dataset_redis_moving_window_expiry(self): limiter = MovingWindowRateLimiter(self.storage) limit = RateLimitItemPerSecond(1000) # 100 routes fake_routes = [uuid4().hex for _ in range(0, 100)] # go as fast as possible in 2 seconds. start = time.time() def smack(e): while not e.is_set(): self.assertTrue(limiter.hit(limit, random.choice(fake_routes))) events = [threading.Event() for _ in range(0, 100)] threads = [threading.Thread(target=smack, args=(e, )) for e in events] [k.start() for k in threads] while time.time() - start < 2: time.sleep(0.1) [k.set() for k in events] time.sleep(2) self.assertTrue( self.storage.storage.keys("%s/*" % limit.namespace) == [])