Skip to content

Commit 22ab20c

Browse files
committed
Clean up python code
1 parent 8d6654a commit 22ab20c

File tree

3 files changed

+66
-36
lines changed

3 files changed

+66
-36
lines changed

libCacheSim-python/libcachesim/eviction.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __repr__(self) -> str:
3232
pass
3333

3434
@abstractmethod
35-
def process_trace(self, reader, max_req=-1, max_sec=-1, start_time=-1, end_time=-1):
35+
def process_trace(self, reader, max_req: int = -1, max_sec: int = -1, start_time: int = -1, end_time: int = -1) -> float:
3636
"""Process a trace with this cache and return miss ratio.
3737
3838
This method processes trace data entirely on the C++ side to avoid
@@ -63,7 +63,7 @@ def init_cache(self, cache_size: int, **kwargs) -> Cache:
6363
def get(self, req: Request) -> bool:
6464
return self.cache.get(req)
6565

66-
def process_trace(self, reader, max_req=-1, max_sec=-1, start_time=-1, end_time=-1):
66+
def process_trace(self, reader, max_req: int = -1, max_sec: int = -1, start_time: int = -1, end_time: int = -1) -> float:
6767
"""Process a trace with this cache and return miss ratio.
6868
6969
This method processes trace data entirely on the C++ side to avoid
@@ -150,9 +150,9 @@ def init_cache(self, cache_size: int, **kwargs):
150150
return Clock_init(cache_size, n_bit_counter, init_freq)
151151

152152
def __repr__(self):
153-
return f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, " \
154-
f"n_bit_counter={self.n_bit_counter}, " \
155-
f"init_freq={self.init_freq})"
153+
return (f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, "
154+
f"n_bit_counter={self.n_bit_counter}, "
155+
f"init_freq={self.init_freq})")
156156

157157

158158
class TwoQ(EvictionPolicy):
@@ -183,9 +183,9 @@ def init_cache(self, cache_size: int, **kwargs):
183183
return TwoQ_init(cache_size, ain_size_ratio, aout_size_ratio)
184184

185185
def __repr__(self):
186-
return f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, " \
187-
f"ain_size_ratio={self.ain_size_ratio}, " \
188-
f"aout_size_ratio={self.aout_size_ratio})"
186+
return (f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, "
187+
f"ain_size_ratio={self.ain_size_ratio}, "
188+
f"aout_size_ratio={self.aout_size_ratio})")
189189

190190

191191
class LRB(EvictionPolicy):
@@ -214,8 +214,8 @@ def init_cache(self, cache_size: int, **kwargs) -> Cache:
214214
return LRB_init(cache_size, objective)
215215

216216
def __repr__(self):
217-
return f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, " \
218-
f"objective={self.objective})"
217+
return (f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, "
218+
f"objective={self.objective})")
219219

220220

221221
class LRU(EvictionPolicy):
@@ -286,10 +286,10 @@ def init_cache(self, cache_size: int, **kwargs):
286286
return S3FIFO_init(cache_size, fifo_size_ratio, ghost_size_ratio, move_to_main_threshold)
287287

288288
def __repr__(self):
289-
return f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, " \
290-
f"fifo_size_ratio={self.fifo_size_ratio}, " \
291-
f"ghost_size_ratio={self.ghost_size_ratio}, " \
292-
f"move_to_main_threshold={self.move_to_main_threshold})"
289+
return (f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, "
290+
f"fifo_size_ratio={self.fifo_size_ratio}, "
291+
f"ghost_size_ratio={self.ghost_size_ratio}, "
292+
f"move_to_main_threshold={self.move_to_main_threshold})")
293293

294294

295295
class Sieve(EvictionPolicy):
@@ -326,8 +326,8 @@ def init_cache(self, cache_size: int, **kwargs):
326326
return ThreeLCache_init(cache_size, objective)
327327

328328
def __repr__(self):
329-
return f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, " \
330-
f"objective={self.objective})"
329+
return (f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, "
330+
f"objective={self.objective})")
331331

332332

333333
class TinyLFU(EvictionPolicy):
@@ -355,9 +355,9 @@ def init_cache(self, cache_size: int, **kwargs):
355355
return TinyLFU_init(cache_size, main_cache, window_size)
356356

357357
def __repr__(self):
358-
return f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, " \
359-
f"main_cache={self.main_cache}, " \
360-
f"window_size={self.window_size})"
358+
return (f"{self.__class__.__name__}(cache_size={self.cache.cache_size}, "
359+
f"main_cache={self.main_cache}, "
360+
f"window_size={self.window_size})")
361361

362362

363363

@@ -508,5 +508,5 @@ def cache_size(self):
508508
return self.cache.cache_size
509509

510510
def __repr__(self):
511-
return f"{self.__class__.__name__}(cache_size={self._cache_size}, " \
512-
f"cache_name='{self.cache_name}', hooks_set={self._hooks_set})"
511+
return (f"{self.__class__.__name__}(cache_size={self._cache_size}, "
512+
f"cache_name='{self.cache_name}', hooks_set={self._hooks_set})")

libCacheSim-python/tests/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def mock_reader():
2626
try:
2727
if hasattr(reader, 'close'):
2828
reader.close()
29-
except:
29+
except Exception: # Be specific about exception type
3030
pass
3131
# Don't explicitly del reader here, let Python handle it
3232
gc.collect()

libCacheSim-python/tests/test_unified_interface.py

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@
2121

2222

2323
def create_trace_reader():
24-
"""Helper function to create a trace reader."""
24+
"""Helper function to create a trace reader.
25+
26+
Returns:
27+
Reader or None: A trace reader instance, or None if trace file not found.
28+
"""
2529
data_file = os.path.join(
2630
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
2731
"data",
@@ -33,24 +37,33 @@ def create_trace_reader():
3337

3438

3539
def create_test_lru_hooks():
36-
"""Create LRU hooks for testing."""
40+
"""Create LRU hooks for testing.
41+
42+
Returns:
43+
tuple: A tuple of (init_hook, hit_hook, miss_hook, eviction_hook, remove_hook)
44+
"""
3745

3846
def init_hook(cache_size):
47+
"""Initialize LRU data structure."""
3948
return OrderedDict()
4049

4150
def hit_hook(lru_dict, obj_id, obj_size):
51+
"""Handle cache hit by moving to end (most recently used)."""
4252
if obj_id in lru_dict:
4353
lru_dict.move_to_end(obj_id)
4454

4555
def miss_hook(lru_dict, obj_id, obj_size):
56+
"""Handle cache miss by adding new object."""
4657
lru_dict[obj_id] = obj_size
4758

4859
def eviction_hook(lru_dict, obj_id, obj_size):
60+
"""Return the least recently used object ID for eviction."""
4961
if lru_dict:
5062
return next(iter(lru_dict))
5163
return obj_id
5264

5365
def remove_hook(lru_dict, obj_id):
66+
"""Remove object from LRU structure."""
5467
lru_dict.pop(obj_id, None)
5568

5669
return init_hook, hit_hook, miss_hook, eviction_hook, remove_hook
@@ -86,22 +99,27 @@ def test_unified_process_trace_interface():
8699
results = {}
87100
for name, cache in caches.items():
88101
# Create fresh reader for each test
89-
reader = create_trace_reader()
90-
if not reader:
91-
continue
102+
test_reader = create_trace_reader()
103+
if not test_reader:
104+
pytest.skip(f"Cannot create reader for {name} test")
92105

93106
# Test process_trace method exists
94107
assert hasattr(cache, 'process_trace'), f"{name} missing process_trace method"
95108

96109
# Test process_trace functionality
97-
miss_ratio = cache.process_trace(reader, max_req=max_requests)
110+
miss_ratio = cache.process_trace(test_reader, max_req=max_requests)
98111
results[name] = miss_ratio
99112

100113
print(f"{name:15s}: miss_ratio = {miss_ratio:.4f}")
101114
print(f" cache stats: {cache.n_obj} objects, {cache.occupied_byte} bytes")
102115

116+
# Verify miss_ratio is valid
117+
assert 0.0 <= miss_ratio <= 1.0, f"{name} returned invalid miss_ratio: {miss_ratio}"
118+
103119
print(f"\nPASS: All {len(caches)} cache policies support unified process_trace interface!")
104-
# Test passes - no explicit return needed for pytest
120+
121+
# Verify we got results for all caches
122+
assert len(results) == len(caches), "Not all caches were tested"
105123

106124

107125
def test_unified_properties_interface():
@@ -134,7 +152,6 @@ def test_unified_properties_interface():
134152
assert cache.cache_size == cache_size, f"{name} cache_size mismatch"
135153

136154
print("PASS: All cache policies support unified properties interface!")
137-
# Test passes - no explicit return needed for pytest
138155

139156

140157
def test_get_interface_consistency():
@@ -163,20 +180,33 @@ def test_get_interface_consistency():
163180
print("Testing get() method with test request...")
164181

165182
for name, cache in caches.items():
183+
# Reset cache state for consistent testing
184+
initial_n_req = cache.n_req
185+
initial_n_obj = cache.n_obj
186+
initial_occupied = cache.occupied_byte
187+
166188
# Test get method exists
167189
assert hasattr(cache, 'get'), f"{name} missing get method"
168190

169-
# Test first access (should be miss)
191+
# Test first access (should be miss for new object)
170192
result = cache.get(test_req)
171193
print(f"{name:15s}: first access = {'HIT' if result else 'MISS'}")
172194

173-
# Test properties updated
174-
assert cache.n_req > 0, f"{name} n_req not updated"
175-
assert cache.n_obj > 0, f"{name} n_obj not updated"
176-
assert cache.occupied_byte > 0, f"{name} occupied_byte not updated"
195+
# Test properties updated correctly
196+
assert cache.n_req > initial_n_req, f"{name} n_req not updated"
197+
if not result: # If it was a miss, object should be added
198+
assert cache.n_obj > initial_n_obj, f"{name} n_obj not updated after miss"
199+
assert cache.occupied_byte > initial_occupied, f"{name} occupied_byte not updated after miss"
200+
201+
# Test second access to same object (should be hit)
202+
second_result = cache.get(test_req)
203+
print(f"{name:15s}: second access = {'HIT' if second_result else 'MISS'}")
204+
205+
# Second access should be a hit (unless cache is too small)
206+
if cache.cache_size >= test_req.obj_size:
207+
assert second_result, f"{name} second access should be a hit"
177208

178209
print("PASS: Get interface consistency test passed!")
179-
# Test passes - no explicit return needed for pytest
180210

181211

182212
if __name__ == "__main__":

0 commit comments

Comments
 (0)