Skip to content

Commit 6c56368

Browse files
committed
Added test for caching decorator
1 parent e99ee9e commit 6c56368

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

pySDC/helpers/spectral_helper.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
def cache(func):
99
"""
1010
Decorator for caching return values of functions.
11+
This is very similar to `functools.cache`, but without the memory leaks (see
12+
https://docs.astral.sh/ruff/rules/cached-instance-method/).
1113
1214
Example:
1315

pySDC/tests/test_helpers/test_spectral_helper.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,30 @@ def test_dealias_MPI(num_procs, axis, bx, bz, nx=32, nz=64, **kwargs):
551551
run_MPI_test(num_procs=num_procs, axis=axis, nx=nx, nz=nz, bx=bx, bz=bz, test='dealias')
552552

553553

554+
@pytest.mark.base
555+
def test_cache_decorator():
556+
from pySDC.helpers.spectral_helper import cache
557+
import numpy as np
558+
559+
class Dummy:
560+
num_calls = 0
561+
562+
@cache
563+
def increment(self, x):
564+
self.num_calls += 1
565+
return x + 1
566+
567+
dummy = Dummy()
568+
values = [0, 1, 1, 0, 3, 1, 2]
569+
unique_vals = np.unique(values)
570+
571+
for x in values:
572+
assert dummy.increment(x) == x + 1
573+
574+
assert dummy.num_calls < len(values)
575+
assert dummy.num_calls == len(unique_vals)
576+
577+
554578
if __name__ == '__main__':
555579
str_to_bool = lambda me: False if me == 'False' else True
556580
str_to_tuple = lambda arg: tuple(int(me) for me in arg.split(','))

0 commit comments

Comments
 (0)