Files
scgenerator/tests/test_cache.py
2024-04-29 09:37:02 +02:00

140 lines
3.3 KiB
Python

import pytest
import scgenerator.cache as scc
from scgenerator.cache import Cache, normalize_path
def test_io():
cache = Cache("Hello")
assert not cache.dir.exists()
cache.reset()
assert cache.dir.exists()
cache.save("a", "bonjour")
assert cache.load("a") == "bonjour"
assert "a" in cache
cache.delete()
assert not cache.dir.exists()
def test_toml():
s1 = """
[config]
plot_range = [750, 1350]
rin_measurement = "./DualComb1GHz_updated_corrected_extrapolated_1GHz_noqn.csv"
num_segments = 31
num_frequencies = 513
noise_seed_start = 3012
anticorrelated_width = true
"""
s2 = """
# some commment
[config]
anticorrelated_width = true
plot_range = [750,1350]
num_segments=31
num_frequencies = 513
noise_seed_start=3012
rin_measurement='./DualComb1GHz_updated_corrected_extrapolated_1GHz_noqn.csv'
"""
s3 = """
# some commment
[config]
anticorrelated_width = true
plot_range = [750,1351]
num_segments=31
num_frequencies = 513
noise_seed_start=3012
rin_measurement='./DualComb1GHz_updated_corrected_extrapolated_1GHz_noqn.csv'
"""
cache1 = Cache.from_toml(s1)
cache3 = Cache.from_toml(s3, create=False)
assert cache1.dir == Cache.from_toml(s2).dir
assert cache1.dir != cache3.dir
assert cache1.dir.exists()
cache1.delete()
assert not cache1.dir.exists()
assert not cache3.dir.exists()
class Stuff:
call_count = 0
@classmethod
def from_other(cls, stuff: str):
cls.call_count += 1
return cls(stuff[:5])
def __init__(self, x):
self.x = x
@pytest.fixture
def cache_for_test():
cache = Cache("Test")
yield cache
cache.delete()
def test_decorator(cache_for_test: Cache):
call_count = 0
@cache_for_test(lambda x: str(x))
def func(x: str) -> str:
nonlocal call_count
call_count += 1
return x + x
@cache_for_test(lambda li: f"{li[0]}-{li[-1]} {len(li)}")
def func2(some_list: list):
nonlocal call_count
call_count += 1
return sum(some_list)
Stuff.from_other = cache_for_test(lambda _, *args: str(args))(Stuff.from_other)
assert func("hello") == "hellohello"
assert func2([0, 1, 2, 80]) == 83
assert func2([0, 1, 2, 80]) == 83
assert (scc.CACHE_DIR / "Test" / "test_decorator._locals_.func hello").exists()
assert (scc.CACHE_DIR / "Test" / "test_decorator._locals_.func2 0-80 4").exists()
assert Stuff.from_other("Bonjour").x == "Bonjo"
assert Stuff.from_other("Bonjour").x == "Bonjo"
assert Stuff.call_count == 1
assert call_count == 2
def test_normalize():
assert normalize_path("abd") == "abd"
assert normalize_path("a/b") == "a_b"
assert normalize_path("bonjour\nsdfk") == "bonjour sdfk"
assert normalize_path("a\\b") == "a_b"
assert (
normalize_path(
"""sdfl asdfk
asd
"""
)
== "sdfl asdfk asd"
)
assert (
normalize_path(
"i=-1 [8.50e-07 9.00e-07 9.44e-07 1.01e-06 1.00e-06 1.05e-06 "
"1.10e-06 1.15e-06\n 1.20e-06 1.25e-06] [1.5e-08]nm.scbin"
)
== "i=-1 [8.50e-07 9.00e-07 9.44e-07 1.01e-06 1.00e-06 1.05e-06 1.10e-06 1.15e-06 "
"1.20e-06 1.25e-06] [1.5e-08]nm.scbin"
)