Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions diskcache/persistent.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,27 @@ def __init__(self, iterable=(), directory=None, maxlen=None):
If directory is None then temporary directory created. The directory
will *not* be automatically removed.

If existing items exceed maxlen, discard items from the left before
appending iterable.

:param iterable: iterable of items to append to deque
:param directory: deque directory (default None)
:param maxlen: maximum number of items (default None, no limit)

"""
self._cache = Cache(directory, eviction_policy='none')
self._maxlen = float('inf') if maxlen is None else maxlen
if maxlen is not None and self._maxlen >= 0:
self.maxlen = self._maxlen
self._extend(iterable)

@classmethod
def fromcache(cls, cache, iterable=(), maxlen=None):
"""Initialize deque using `cache`.

If existing items exceed maxlen, discard items from the left before
appending iterable.

>>> cache = Cache()
>>> deque = Deque.fromcache(cache, [5, 6, 7, 8])
>>> deque.cache is cache
Expand All @@ -106,13 +115,16 @@ def fromcache(cls, cache, iterable=(), maxlen=None):

:param Cache cache: cache to use
:param iterable: iterable of items
:param maxlen: maximum number of items (default None, no limit)
:return: initialized Deque

"""
# pylint: disable=no-member,protected-access
self = cls.__new__(cls)
self._cache = cache
self._maxlen = float('inf') if maxlen is None else maxlen
if maxlen is not None and self._maxlen >= 0:
self.maxlen = self._maxlen
self._extend(iterable)
return self

Expand Down
99 changes: 99 additions & 0 deletions tests/test_deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pickle
import shutil
import tempfile
from collections import deque as memory_deque
from unittest import mock

import pytest
Expand Down Expand Up @@ -50,6 +51,104 @@ def test_init():
rmdir(directory)


@pytest.mark.parametrize('fromcache', [False, True])
@pytest.mark.parametrize('maxlen', [None, 0, 1, 3, 5, 8])
@pytest.mark.parametrize('iterable', [(), (5, 6)])
def test_init_existing_cache_maxlen(tmp_path, fromcache, maxlen, iterable):
directory = str(tmp_path / 'deque')
original = dc.Deque(range(5), directory=directory)
original.cache.close()

expected = memory_deque(range(5), maxlen=maxlen)
expected.extend(iterable)

if fromcache:
cache = dc.Cache(directory, eviction_policy='none')
try:
bounded = dc.Deque.fromcache(cache, iterable, maxlen=maxlen)
assert bounded.cache is cache
except BaseException:
cache.close()
raise
else:
bounded = dc.Deque(iterable, directory=directory, maxlen=maxlen)

try:
assert list(bounded) == list(expected)
assert bounded.maxlen == (float('inf') if maxlen is None else maxlen)

bounded.append(7)
expected.append(7)
assert list(bounded) == list(expected)

bounded.appendleft(-1)
expected.appendleft(-1)
assert list(bounded) == list(expected)
finally:
bounded.cache.close()

persisted = dc.Deque(directory=directory)
try:
assert list(persisted) == list(expected)
finally:
persisted.cache.close()


@pytest.mark.parametrize('fromcache', [False, True])
def test_init_unbounded_does_not_start_transaction(tmp_path, fromcache):
directory = str(tmp_path / 'deque')
cache = dc.Cache(directory, eviction_policy='none')
for value in range(5):
cache.push(value)
statements = []
cache._con.set_trace_callback(statements.append)
try:
# Observe Deque initialization after Cache has opened the database.
with mock.patch('diskcache.persistent.Cache', return_value=cache):
if fromcache:
unbounded = dc.Deque.fromcache(cache)
else:
unbounded = dc.Deque(directory=directory)
cache._con.set_trace_callback(None)
assert not any(
sql.lstrip().upper().startswith('BEGIN') for sql in statements
), statements
assert list(unbounded) == list(range(5))
assert unbounded.maxlen == float('inf')
finally:
cache._con.set_trace_callback(None)
cache.close()


@pytest.mark.parametrize('fromcache', [False, True])
def test_init_negative_maxlen_preserves_existing_data(tmp_path, fromcache):
directory = str(tmp_path / 'deque')
original = dc.Deque(range(5), directory=directory)
original.cache.close()
cache = dc.Cache(directory, eviction_policy='none') if fromcache else None
try:
try:
if fromcache:
bounded = dc.Deque.fromcache(cache, maxlen=-1)
else:
bounded = dc.Deque(directory=directory, maxlen=-1)
except ValueError:
# Negative-limit validation is separate work. Either outcome must
# preserve the data that was already stored in the cache.
pass
else:
bounded.cache.close()
finally:
if cache is not None:
cache.close()

persisted = dc.Deque(directory=directory)
try:
assert list(persisted) == list(range(5))
finally:
persisted.cache.close()


def test_getsetdel(deque):
sequence = list('abcde')
assert len(deque) == 0
Expand Down