From f6d10946c6a110c5f912cde8734c91935a73af86 Mon Sep 17 00:00:00 2001 From: Alok Saldanha Date: Thu, 19 Sep 2019 11:48:39 -0400 Subject: [PATCH] #4 added failing test for cache pruning --- cellxgene_gateway/prune_process_cache.py | 25 +++++++++++++---------- tests/test_prune_process_cache.py | 26 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 tests/test_prune_process_cache.py diff --git a/cellxgene_gateway/prune_process_cache.py b/cellxgene_gateway/prune_process_cache.py index db70807..a3c891e 100644 --- a/cellxgene_gateway/prune_process_cache.py +++ b/cellxgene_gateway/prune_process_cache.py @@ -21,17 +21,20 @@ class PruneProcessCache: def __call__(self): while True: time.sleep(60) + self.prune() - timestamp = current_time_stamp() + def prune(self): + timestamp = current_time_stamp() - processes_to_delete = [] - for p in self.cache.entry_list: - if timestamp - p.timestamp > (3600 if ttl is None else ttl): - processes_to_delete.append(p) - processes_to_delete + processes_to_delete = [] + for p in self.cache.entry_list: + if timestamp - p.timestamp > (3600 if ttl is None else ttl): + processes_to_delete.append(p) + processes_to_delete + + for process in processes_to_delete: + try: + cache.prune(process) + except Exception: + logging.getLogger("werkzeug").exception("failed to prune process") - for process in processes_to_delete: - try: - cache.prune(process) - except Exception: - logging.getLogger("werkzeug").exception("failed to prune process") diff --git a/tests/test_prune_process_cache.py b/tests/test_prune_process_cache.py new file mode 100644 index 0000000..fe84677 --- /dev/null +++ b/tests/test_prune_process_cache.py @@ -0,0 +1,26 @@ +import unittest +from unittest.mock import MagicMock, patch +from cellxgene_gateway.cache_entry import CacheEntry +from cellxgene_gateway.backend_cache import BackendCache + +class TestPruneProcessCache(unittest.TestCase): + @patch('cellxgene_gateway.util.current_time_stamp', new=lambda:0) + @patch('cellxgene_gateway.env.ttl', new='10') + @patch('cellxgene_gateway.cache_entry.CacheEntry') + @patch('cellxgene_gateway.cache_entry.CacheEntry') + def test_GIVEN_one_old_one_new_THEN_prune_old(self, old, new): + from cellxgene_gateway.prune_process_cache import PruneProcessCache + + cache = BackendCache() + old.timestamp = -100 + cache.entry_list.append(old) + new.timestamp = -5 + cache.entry_list.append(new) + self.assertEqual(len(cache.entry_list), 2) + ppc = PruneProcessCache(cache) + ppc.prune() + self.assertEqual(len(cache.entry_list), 1) + self.assertEqual(cache.entry_list[0], new) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file