def test_record_usage(self): self.now = 24 * 3600 + 5 ts = ratelimit.get_timeslice(3600) ratelimit.record_usage('a', ts) self.assertEquals(1, self.cache['rl:a-000000']) ratelimit.record_usage('a', ts) self.assertEquals(2, self.cache['rl:a-000000']) self.now = 24 * 3600 + 5 * 3600 ts = ratelimit.get_timeslice(3600) ratelimit.record_usage('a', ts) self.assertEquals(1, self.cache['rl:a-050000'])
def test_record_usage_across_slice_expiration(self): self.now = 24 * 3600 + 5 ts = ratelimit.get_timeslice(3600) real_incr = self.cache.incr evicted = False def fake_incr(key): if evicted: del self.cache[key] raise pylibmc.NotFound() return real_incr(key) with patch.object(self.cache, 'incr', fake_incr): # Forcibly evict the key before incr() is called, but after the # initial add() call inside record_usage(). evicted = True ratelimit.record_usage('a', ts) self.assertEquals(1, self.cache['rl:a-000000'])
def test_make_ratelimit_cache_key_1w(self): self.now = 7 * 24 * 3600 + 5 ts = ratelimit.get_timeslice(24 * 3600) key = ratelimit._make_ratelimit_cache_key('a', ts) self.assertEquals('rl:a-@604800', key)
def test_make_ratelimit_cache_key_1h(self): self.now = 3650 ts = ratelimit.get_timeslice(3600) key = ratelimit._make_ratelimit_cache_key('a', ts) self.assertEquals('rl:a-010000', key)
def test_make_ratelimit_cache_key_1m(self): self.now = 65 ts = ratelimit.get_timeslice(60) key = ratelimit._make_ratelimit_cache_key('a', ts) self.assertEquals('rl:a-000100', key)
def test_make_ratelimit_cache_key_1s(self): self.now = 14 ts = ratelimit.get_timeslice(1) key = ratelimit._make_ratelimit_cache_key('a', ts) self.assertEquals('rl:a-000014', key)
def test_get_timeslice(self): self.now = 125 ts = ratelimit.get_timeslice(60) self.assertEquals(120, ts.beginning) self.assertEquals(180, ts.end) self.assertEquals(55, ts.remaining)
def test_get_usage(self): self.now = 24 * 3600 + 5 * 3600 ts = ratelimit.get_timeslice(3600) self.assertEquals(None, ratelimit.get_usage('a', ts)) ratelimit.record_usage('a', ts) self.assertEquals(1, ratelimit.get_usage('a', ts))