1
from mako.util import LRUCache
2
import string, unittest, time, random
7
def __init__(self, id):
11
return "item id %d" % self.id
13
class LRUTest(unittest.TestCase):
17
l = LRUCache(10, threshold=.2)
19
for id in range(1,20):
22
# first couple of items should be gone
23
self.assert_(not l.has_key(1))
24
self.assert_(not l.has_key(2))
26
# next batch over the threshold of 10 should be present
27
for id in range(11,20):
28
self.assert_(l.has_key(id))
38
self.assert_(not l.has_key(11))
39
self.assert_(not l.has_key(13))
41
for id in (25, 24, 23, 14, 12, 19, 18, 17, 16, 15):
42
self.assert_(l.has_key(id))
44
def disabled_test_threaded(self):
48
hot_zone = range(30,40)
49
cache = LRUCache(size, threshold)
52
class Element(object):
53
def __init__(self, id):
57
# return an element. we will favor ids in the relatively small
58
# "hot zone" 25% of the time.
60
if random.randint(1,4) == 1:
61
return hot_zone[random.randint(0, len(hot_zone) - 1)]
63
return random.randint(1, all_elems)
78
time.sleep(random.random() / 1000)
80
thread.start_new_thread(request_elem, ())
82
# assert size doesn't grow unbounded, doesnt shrink well below size
85
print "size:", len(cache)
86
assert len(cache) < size + size * threshold * 2
87
assert len(cache) > size - (size * .1)
89
# computs the average number of times a range of elements were "reused",
90
# i.e. without being removed from the cache.
91
def average_regets_in_range(start, end):
92
elem = [e for e in cache.values() if e.id >= start and e.id <= end]
95
avg = sum([e.regets for e in elem]) / len(elem)
98
hotzone_avg = average_regets_in_range(30, 40)
99
control_avg = average_regets_in_range(450,760)
100
total_avg = average_regets_in_range(0, 2000)
102
# hotzone should be way above the others
103
print "total fetches", total[0], "hotzone", hotzone_avg, "control", control_avg, "total", total_avg
105
assert hotzone_avg > total_avg * 5 > control_avg * 5
108
if __name__ == "__main__":