Skip to content
Snippets Groups Projects
Commit cd42d4a8 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

fix cacheDict

parent 2f0ec910
No related branches found
No related tags found
No related merge requests found
import time
import typing as tp
from satella.coding.structures import CacheDict
from satella.time import measure
from .. import Metric
from ..metric_types import ClicksPerTimeUnitMetric
from ..metric_types.measurable_mixin import MeasurableMixin
class MetrifiedCacheDict(CacheDict):
......@@ -22,20 +21,22 @@ class MetrifiedCacheDict(CacheDict):
cache_hits: tp.Optional[Metric] = None,
cache_miss: tp.Optional[Metric] = None,
refreshes: tp.Optional[Metric] = None,
how_long_refresh_takes: tp.Optional[Metric] = None):
if refreshes or how_long_refresh_takes:
how_long_refresh_takes: tp.Optional[MeasurableMixin] = None):
if refreshes:
old_value_getter = value_getter
def value_getter_replacement(item):
with measure() as measurement:
try:
return value_getter(item)
finally:
if self.refreshes:
self.refreshes.runtime(+1)
if self.how_long_refresh_takes:
self.how_long_refresh_takes.runtime(measurement())
try:
return old_value_getter(item)
finally:
if self.refreshes:
self.refreshes.runtime(+1)
value_getter = value_getter_replacement
if how_long_refresh_takes:
value_getter = how_long_refresh_takes.measure(value_getter=time_getter)(value_getter)
super().__init__(stale_interval, expiration_interval, value_getter,
value_getter_executor, cache_failures_interval, time_getter,
default_value_factory)
......
......@@ -18,10 +18,12 @@ class TestThreadPoolExecutor(unittest.TestCase):
cache_hits = getMetric('cachedict.hits', 'counter')
cache_miss = getMetric('cachedict.miss', 'counter')
refreshes = getMetric('refreshes', 'counter')
how_long_takes = getMetric('how_long_takes', 'summary')
value = 2
def getter(key):
nonlocal value
time.sleep(0.5)
if value is None:
raise KeyError()
else:
......@@ -29,11 +31,13 @@ class TestThreadPoolExecutor(unittest.TestCase):
mcd = MetrifiedCacheDict(1, 2, getter, cache_hits=cache_hits,
cache_miss=cache_miss,
refreshes=refreshes)
refreshes=refreshes,
how_long_refresh_takes=how_long_takes)
mcd[2]
self.assertEqual(n_th(cache_hits.to_metric_data().values).value, 0)
self.assertEqual(n_th(cache_miss.to_metric_data().values).value, 1)
self.assertEqual(n_th(refreshes.to_metric_data().values).value, 1)
self.assertGreaterEqual(n_th(how_long_takes.to_metric_data().values).value, 0.5)
mcd[2]
self.assertEqual(n_th(cache_hits.to_metric_data().values).value, 1)
self.assertEqual(n_th(cache_miss.to_metric_data().values).value, 1)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment