Skip to content

Commit f1da7a5

Browse files
committed
Update tests
1 parent 88bcc04 commit f1da7a5

8 files changed

Lines changed: 35 additions & 80 deletions

File tree

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cachebox/_core.pyi

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,7 @@ class BaseCacheImpl(typing.Generic[KT, VT]):
157157
*args: typing.Any,
158158
**kwargs: typing.Any,
159159
) -> None: ...
160-
def get(
161-
self, key: KT, default: typing.Optional[DT] = None
162-
) -> typing.Union[VT, DT]: ...
160+
def get(self, key: KT, default: typing.Optional[DT] = None) -> typing.Union[VT, DT]: ...
163161
def __getitem__(self, key: KT) -> VT: ...
164162
def setdefault(
165163
self,

cachebox/_wrappers.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,7 @@ def _cached_wrapper_without_lock(
7171

7272
# Per-instance caches receive `self` as args[0]; exclude it from the ke
7373
_make_key = (
74-
(lambda a, k: key_maker(*a[1:], **k))
75-
if cache_is_fn
76-
else (lambda a, k: key_maker(*a, **k))
74+
(lambda a, k: key_maker(*a[1:], **k)) if cache_is_fn else (lambda a, k: key_maker(*a, **k))
7775
)
7876

7977
hits = 0
@@ -145,9 +143,7 @@ def _async_cached_wrapper_without_lock(
145143

146144
# Per-instance caches receive `self` as args[0]; exclude it from the ke
147145
_make_key = (
148-
(lambda a, k: key_maker(*a[1:], **k))
149-
if cache_is_fn
150-
else (lambda a, k: key_maker(*a, **k))
146+
(lambda a, k: key_maker(*a[1:], **k)) if cache_is_fn else (lambda a, k: key_maker(*a, **k))
151147
)
152148

153149
hits = 0
@@ -209,9 +205,7 @@ def _cached_wrapper(
209205

210206
# Per-instance caches receive `self` as args[0]; exclude it from the key
211207
_make_key = (
212-
(lambda a, k: key_maker(*a[1:], **k))
213-
if cache_is_fn
214-
else (lambda a, k: key_maker(*a, **k))
208+
(lambda a, k: key_maker(*a[1:], **k)) if cache_is_fn else (lambda a, k: key_maker(*a, **k))
215209
)
216210

217211
hits = 0
@@ -313,9 +307,7 @@ def _async_cached_wrapper(
313307
):
314308
cache_is_fn = callable(cache)
315309
_make_key = (
316-
(lambda a, k: key_maker(*a[1:], **k))
317-
if cache_is_fn
318-
else (lambda a, k: key_maker(*a, **k))
310+
(lambda a, k: key_maker(*a[1:], **k)) if cache_is_fn else (lambda a, k: key_maker(*a, **k))
319311
)
320312

321313
hits = 0

cachebox/utils.py

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -366,16 +366,9 @@ def __repr__(self) -> str:
366366
def _cast_lock(
367367
iscoroutinefunction: bool,
368368
lock: (
369-
typing.Type[AbstractContextManager]
370-
| typing.Type[AbstractAsyncContextManager]
371-
| bool
372-
| None
369+
typing.Type[AbstractContextManager] | typing.Type[AbstractAsyncContextManager] | bool | None
373370
) = True,
374-
) -> (
375-
typing.Type[AbstractContextManager]
376-
| typing.Type[AbstractAsyncContextManager]
377-
| None
378-
):
371+
) -> typing.Type[AbstractContextManager] | typing.Type[AbstractAsyncContextManager] | None:
379372
import _thread
380373
import asyncio
381374
import threading
@@ -388,18 +381,12 @@ def _cast_lock(
388381

389382
if iscoroutinefunction:
390383
if not hasattr(lock, "__aenter__"):
391-
raise TypeError(
392-
"For async functions, you cannot use a regular synchronous lock."
393-
)
384+
raise TypeError("For async functions, you cannot use a regular synchronous lock.")
394385

395386
return typing.cast(typing.Type[AbstractAsyncContextManager], lock)
396387

397388
# threading.Lock, threading.RLock and _thread.allocate_lock are function
398-
if (
399-
lock is threading.Lock
400-
or lock is threading.RLock
401-
or lock is _thread.allocate_lock
402-
):
389+
if lock is threading.Lock or lock is threading.RLock or lock is _thread.allocate_lock:
403390
return typing.cast(typing.Type[AbstractContextManager], lock)
404391

405392
if not hasattr(lock, "__enter__"):
@@ -416,10 +403,7 @@ def cached(
416403
copy_level: int = 1,
417404
postprocess: _PostProcess | None = postprocess_copy_mutables,
418405
lock: (
419-
typing.Type[AbstractContextManager]
420-
| typing.Type[AbstractAsyncContextManager]
421-
| bool
422-
| None
406+
typing.Type[AbstractContextManager] | typing.Type[AbstractAsyncContextManager] | bool | None
423407
) = True,
424408
) -> typing.Callable[[FT], FT]:
425409
"""
@@ -495,9 +479,7 @@ def decorator(func: FT) -> FT:
495479
lock_type = _cast_lock(iscoroutinefunction, lock)
496480

497481
if not iscoroutinefunction and inspect.iscoroutinefunction(callback):
498-
raise TypeError(
499-
"For sync functions, you cannot use a asynchronous callback"
500-
)
482+
raise TypeError("For sync functions, you cannot use a asynchronous callback")
501483

502484
if lock_type:
503485
builder = _async_cached_wrapper if iscoroutinefunction else _cached_wrapper

src/internal/utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub unsafe fn pyobject_hash(
1717
let py_hash = pyo3::ffi::PyObject_Hash(arg1);
1818
if std::hint::unlikely(py_hash == -1) {
1919
// SAFETY: PyObject_Hash never returns -1 on success.
20-
return Err(pyo3::PyErr::take(py).unwrap_unchecked());
20+
return Err(pyo3::PyErr::take(py).unwrap());
2121
}
2222

2323
Ok(py_hash as u64)

tests/mixins.py

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -762,9 +762,7 @@ def __hash__(self) -> int:
762762

763763

764764
class SweepIntervalMixin(BaseMixin):
765-
def _create_sweep_cache(
766-
self, *args, **kwds
767-
) -> cachebox.TTLCache | cachebox.VTTLCache:
765+
def _create_sweep_cache(self, *args, **kwds) -> cachebox.TTLCache | cachebox.VTTLCache:
768766
return typing.cast(
769767
cachebox.TTLCache | cachebox.VTTLCache,
770768
self.create_cache(*args, **kwds),
@@ -787,19 +785,15 @@ def test_numeric_sweep_interval_starts_thread(self):
787785
cache.stop_sweeper()
788786

789787
def test_timedelta_sweep_interval_starts_thread(self):
790-
cache = self._create_sweep_cache(
791-
maxsize=10, sweep_interval=timedelta(seconds=1)
792-
)
788+
cache = self._create_sweep_cache(maxsize=10, sweep_interval=timedelta(seconds=1))
793789
try:
794790
assert cache._thread is not None
795791
assert cache._thread.is_alive()
796792
finally:
797793
cache.stop_sweeper()
798794

799795
def test_timedelta_converted_to_seconds(self):
800-
cache = self._create_sweep_cache(
801-
maxsize=10, sweep_interval=timedelta(seconds=5)
802-
)
796+
cache = self._create_sweep_cache(maxsize=10, sweep_interval=timedelta(seconds=5))
803797
try:
804798
assert cache.sweep_interval == 5.0
805799
finally:
@@ -813,9 +807,7 @@ def test_sweep_interval_stored_as_float(self):
813807
cache.stop_sweeper()
814808

815809
def test_sweep_interval_below_1_raises(self):
816-
with pytest.raises(
817-
ValueError, match="sweep_interval must be more than 1 seconds"
818-
):
810+
with pytest.raises(ValueError, match="sweep_interval must be more than 1 seconds"):
819811
self._create_sweep_cache(maxsize=10, sweep_interval=0.5)
820812

821813
def test_sweep_interval_zero_raises(self):
@@ -1032,9 +1024,7 @@ def test_fuzzy_keys_values_items_are_consistent(self, pairs):
10321024
cache_items = dict(c.items())
10331025
assert cache_items == truth
10341026
assert set(c.keys()) == set(truth.keys())
1035-
assert sorted(str(v) for v in c.values()) == sorted(
1036-
str(v) for v in truth.values()
1037-
)
1027+
assert sorted(str(v) for v in c.values()) == sorted(str(v) for v in truth.values())
10381028

10391029
@given(key=hashable_keys, existing=any_value, default=any_value)
10401030
def test_fuzzy_setdefault_never_overwrites_existing(self, key, existing, default):
@@ -1056,12 +1046,8 @@ def test_fuzzy_copy_equals_original(self, pairs):
10561046
c.insert(k, v)
10571047
assert c.copy() == c
10581048

1059-
@given(
1060-
key=hashable_keys, value=any_value, new_key=hashable_keys, new_value=any_value
1061-
)
1062-
def test_fuzzy_copy_is_independent_of_original(
1063-
self, key, value, new_key, new_value
1064-
):
1049+
@given(key=hashable_keys, value=any_value, new_key=hashable_keys, new_value=any_value)
1050+
def test_fuzzy_copy_is_independent_of_original(self, key, value, new_key, new_value):
10651051
assume(new_key != key)
10661052
c = self.create_cache(maxsize=0)
10671053
c.insert(key, value)

tests/test_impls.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1116,19 +1116,15 @@ def test_last_returns_newest_key(self):
11161116

11171117
def test_first_with_positive_n_browses_in_insertion_order(self):
11181118
"""first(n) must walk forward through insertion order."""
1119-
cache = self.create_cache(
1120-
4, [(10, "a"), (20, "b"), (30, "c"), (40, "d")], global_ttl=10
1121-
)
1119+
cache = self.create_cache(4, [(10, "a"), (20, "b"), (30, "c"), (40, "d")], global_ttl=10)
11221120
assert cache.first(0) == 10
11231121
assert cache.first(1) == 20
11241122
assert cache.first(2) == 30
11251123
assert cache.first(3) == 40
11261124

11271125
def test_first_with_negative_n_browses_from_end(self):
11281126
"""first(-1) is an alias for last(); first(-2) is the second newest."""
1129-
cache = self.create_cache(
1130-
4, [(10, "a"), (20, "b"), (30, "c"), (40, "d")], global_ttl=10
1131-
)
1127+
cache = self.create_cache(4, [(10, "a"), (20, "b"), (30, "c"), (40, "d")], global_ttl=10)
11321128
assert cache.first(-1) == 40
11331129
assert cache.first(-2) == 30
11341130

@@ -1750,9 +1746,7 @@ def test_get_with_expire(self):
17501746
time.sleep(0.1)
17511747
value, dur = obj.get_with_expire(1)
17521748
assert 1 == value
1753-
assert isinstance(dur, float) and 10 > dur > 9, (
1754-
"10 > dur > 9 failed [dur: %f]" % dur
1755-
)
1749+
assert isinstance(dur, float) and 10 > dur > 9, "10 > dur > 9 failed [dur: %f]" % dur
17561750

17571751
obj.insert(1, 1, None)
17581752
time.sleep(0.1)
@@ -1775,9 +1769,7 @@ def test_pop_with_expire(self):
17751769
time.sleep(0.1)
17761770
value, dur = obj.pop_with_expire(1)
17771771
assert 1 == value
1778-
assert isinstance(dur, float) and 10 > dur > 9, (
1779-
"10 > dur > 9 failed [dur: %f]" % dur
1780-
)
1772+
assert isinstance(dur, float) and 10 > dur > 9, "10 > dur > 9 failed [dur: %f]" % dur
17811773

17821774
obj.insert(1, 1, None)
17831775
time.sleep(0.1)
@@ -1801,15 +1793,11 @@ def test_popitem_with_expire(self):
18011793
time.sleep(0.1)
18021794
key, value, dur = obj.popitem_with_expire()
18031795
assert (1, 1) == (key, value)
1804-
assert isinstance(dur, float) and 10 > dur > 9, (
1805-
"10 > dur > 9 failed [dur: %f]" % dur
1806-
)
1796+
assert isinstance(dur, float) and 10 > dur > 9, "10 > dur > 9 failed [dur: %f]" % dur
18071797

18081798
key, value, dur = obj.popitem_with_expire()
18091799
assert (2, 2) == (key, value)
1810-
assert isinstance(dur, float) and 20 > dur > 19, (
1811-
"20 > dur > 19 failed [dur: %f]" % dur
1812-
)
1800+
assert isinstance(dur, float) and 20 > dur > 19, "20 > dur > 19 failed [dur: %f]" % dur
18131801

18141802
with pytest.raises(KeyError):
18151803
obj.popitem_with_expire()

tests/test_utils.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import platform
23
import threading
34
import time
45
import typing
@@ -574,6 +575,10 @@ def run():
574575
assert "err" in result
575576

576577

578+
@pytest.mark.skipif(
579+
platform.python_implementation() == "PyPy",
580+
reason="https://github.com/PyO3/pyo3/issues/6109",
581+
)
577582
def test_recursive_cached_issue_54(random_cache_impl: type[cachebox.BaseCacheImpl]):
578583
# https://github.com/awolverp/cachebox/issues/54
579584

@@ -609,6 +614,10 @@ async def run():
609614
assert "err" in result
610615

611616

617+
@pytest.mark.skipif(
618+
platform.python_implementation() == "PyPy",
619+
reason="https://github.com/PyO3/pyo3/issues/6109",
620+
)
612621
@pytest.mark.asyncio
613622
async def test_async_recursive_cached_issue_54(
614623
random_cache_impl: type[cachebox.BaseCacheImpl],

0 commit comments

Comments
 (0)