summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/tests/test_media_cache.py
blob: b66c448832e68da5b04b582926450c21814a2f4f (plain) (blame)
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
"""Tests for media_cache.py — TMDB/thumbnail cache and its pruning obligation."""

import time

import pytest

from meshbay_node.media_cache import MediaCache, TMDB_META_TTL_SECS


@pytest.fixture
async def cache(tmp_path):
    c = MediaCache(db_path=tmp_path / "media_cache.db")
    await c.open()
    yield c
    await c.close()


@pytest.mark.asyncio
async def test_file_tmdb_round_trip(cache):
    assert await cache.get_file_tmdb("file1") is None

    await cache.set_file_tmdb("file1", "12345", "movie")

    assert await cache.get_file_tmdb("file1") == ("12345", "movie")


@pytest.mark.asyncio
async def test_tmdb_meta_round_trip(cache):
    assert await cache.get_tmdb_meta("12345", "movie") is None

    await cache.set_tmdb_meta("12345", "movie", {"title": "A Movie", "vote_average": 7.5})

    meta = await cache.get_tmdb_meta("12345", "movie")
    assert meta == {"title": "A Movie", "vote_average": 7.5}


@pytest.mark.asyncio
async def test_tmdb_meta_expires_after_ttl(cache):
    await cache._db.execute(
        "INSERT INTO tmdb_meta (tmdb_id, media_type, json, fetched_at) VALUES (?, ?, ?, ?)",
        ("999", "movie", '{"title": "Old"}', time.time() - TMDB_META_TTL_SECS - 1),
    )
    await cache._db.commit()

    assert await cache.get_tmdb_meta("999", "movie") is None


@pytest.mark.asyncio
async def test_thumb_round_trip(cache):
    assert await cache.get_thumb("thumbhash1") is None

    await cache.put_thumb("thumbhash1", "file1", b"\xff\xd8fakejpeg")

    assert await cache.get_thumb("thumbhash1") == b"\xff\xd8fakejpeg"


@pytest.mark.asyncio
async def test_prune_file_removes_thumb_and_mapping_but_not_shared_meta(cache):
    # Two episodes of the same show share one tmdb_meta row (§2's stated case).
    await cache.set_file_tmdb("ep1", "555", "tv")
    await cache.set_file_tmdb("ep2", "555", "tv")
    await cache.set_tmdb_meta("555", "tv", {"name": "A Show"})
    await cache.put_thumb("thumb-ep1", "ep1", b"jpeg-bytes-1")

    await cache.prune_file("ep1")

    assert await cache.get_file_tmdb("ep1") is None
    assert await cache.get_thumb("thumb-ep1") is None
    # ep2's own mapping and the shared show metadata both survive
    assert await cache.get_file_tmdb("ep2") == ("555", "tv")
    assert await cache.get_tmdb_meta("555", "tv") == {"name": "A Show"}