def test_fixed_window_with_elastic_expiry_memcache_concurrency(self): storage = MemcachedStorage('memcached://localhost:11211') limiter = FixedWindowElasticExpiryRateLimiter(storage) start = int(time.time()) limit = RateLimitItemPerSecond(100, 2) def _c(): for i in range(0,50): limiter.hit(limit) t1, t2 = threading.Thread(target=_c), threading.Thread(target=_c) t1.start(), t2.start() [t1.join(), t2.join()] self.assertEqual(limiter.get_window_stats(limit)[1], 0) self.assertTrue(start + 2 <= limiter.get_window_stats(limit)[0] <= start + 3) self.assertEqual(storage.get(limit.key_for()), 100)
def test_clear(self): storage = MemcachedStorage("memcached://localhost:22122") limiter = FixedWindowRateLimiter(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_fixed_window_with_elastic_expiry_memcache_concurrency(self): storage = MemcachedStorage('memcached://localhost:11211') limiter = FixedWindowElasticExpiryRateLimiter(storage) start = int(time.time()) limit = RateLimitItemPerSecond(100, 2) def _c(): for i in range(0, 50): limiter.hit(limit) t1, t2 = threading.Thread(target=_c), threading.Thread(target=_c) t1.start(), t2.start() [t1.join(), t2.join()] self.assertEqual(limiter.get_window_stats(limit)[1], 0) self.assertTrue( start + 2 <= limiter.get_window_stats(limit)[0] <= start + 3) self.assertEqual(storage.get(limit.key_for()), 100)
def test_fixed_window_with_elastic_expiry_memcache(self): storage = MemcachedStorage('memcached://localhost:11211') limiter = FixedWindowElasticExpiryRateLimiter(storage) limit = RateLimitItemPerSecond(10, 2) self.assertTrue(all([limiter.hit(limit) for _ in range(0, 10)])) time.sleep(1) self.assertFalse(limiter.hit(limit)) time.sleep(1) self.assertFalse(limiter.hit(limit))
def test_fixed_window_with_elastic_expiry(self): storage = MemcachedStorage("memcached://localhost:22122") limiter = FixedWindowElasticExpiryRateLimiter(storage) per_sec = RateLimitItemPerSecond(2, 2) self.assertTrue(limiter.hit(per_sec)) self.assertTrue(limiter.hit(per_sec)) time.sleep(1) self.assertFalse(limiter.test(per_sec)) time.sleep(1) self.assertTrue(limiter.test(per_sec))
def test_memcached(self): storage = MemcachedStorage("memcached://localhost:11211") limiter = FixedWindowRateLimiter(storage) per_min = RateLimitItemPerSecond(10) start = time.time() count = 0 while time.time() - start < 0.5 and count < 10: self.assertTrue(limiter.hit(per_min)) count += 1 self.assertFalse(limiter.hit(per_min)) while time.time() - start <= 1: time.sleep(0.1) self.assertTrue(limiter.hit(per_min))
def test_moving_window_memcached(self): storage = MemcachedStorage('memcacheD://localhost:11211') self.assertRaises(NotImplementedError, MovingWindowRateLimiter, storage)
def setUp(self): pymemcache.client.Client(('localhost', 11211)).flush_all() self.storage = MemcachedStorage("memcached://localhost:11211")