File: test_filecache.py

package info (click to toggle)
python-ase 3.22.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 14,344 kB
  • sloc: python: 126,379; xml: 946; makefile: 111; javascript: 47
file content (80 lines) | stat: -rw-r--r-- 1,807 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import pytest
from ase.utils.filecache import MultiFileJSONCache, CombinedJSONCache, Locked


pytestmark = pytest.mark.usefixtures('testdir')


@pytest.fixture
def cache():
    return MultiFileJSONCache('cache')


def sample_dict():
    return {'hello': [1, 2, 3], 'world': 'grumble'}


def test_basic(cache):
    assert len(cache) == 0

    cache['hello'] = 'grumble'
    assert len(cache) == 1
    assert 'hello' in cache

    grumble = cache.pop('hello')
    assert grumble == 'grumble'
    assert 'hello' not in cache
    assert len(cache) == 0


@pytest.mark.parametrize('dct', [
    {},
    sample_dict(),
])
def test_cache(dct, cache):
    cache.update(dct)
    assert dict(cache) == dct


def test_combine(cache):
    dct = sample_dict()
    cache.update(dct)
    combined = cache.combine()
    assert dict(combined) == dct


def test_split():
    dct = sample_dict()
    combined = CombinedJSONCache.dump_cache('cache', dct)
    assert dict(combined) == dct
    cache = combined.split()
    assert dict(cache) == dct
    assert len(combined) == 0


def test_lock(cache):
    with cache.lock('hello'):
        # When element is locked but nothing is written, the
        # cache is defined to "contain" None
        assert 'hello' in cache
        assert cache['hello'] is None

        # Other keys should function as normal:
        cache['xx'] = 1
        assert cache['xx'] == 1


def test_already_locked(cache):
    with cache.lock('hello') as handle:
        assert handle is not None
        with cache.lock('hello') as otherhandle:
            assert otherhandle is None

        with pytest.raises(Locked):
            cache['hello'] = 'world'


def test_no_overwrite_combine(cache):
    cache.combine()
    with pytest.raises(RuntimeError, match='Already exists'):
        cache.combine()