summaryrefslogtreecommitdiffstatshomepage
path: root/tests/api/test_archive.py
blob: 0ef3425880523209c84f3bdf48382ab50cc6a990 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import os
from datetime import datetime as dt
from pathlib import Path

import hircine.config
import hircine.db as database
import hircine.thumbnailer as thumb
import pytest
from conftest import DB, Response
from hircine.db.models import Archive, Comic, Image, Page
from sqlalchemy import select


@pytest.fixture
def query_archive(execute_id):
    query = """
    query archive($id: Int!) {
        archive(id: $id) {
            __typename
            ... on FullArchive {
                id
                name
                createdAt
                mtime
                size
                path
                pageCount
                organized
                comics {
                    __typename
                    id
                }
                cover {
                    __typename
                    id
                }
                pages {
                    __typename
                    id
                    image {
                        __typename
                        id
                    }
                }
            }
            ... on Error {
                message
            }
            ... on IDNotFoundError {
                id
            }
        }
    }
    """

    return execute_id(query)


@pytest.fixture
def query_archives(execute):
    query = """
    query archives {
        archives {
            __typename
            count
            edges {
                id
                name
                size
                pageCount
                organized
                cover {
                    __typename
                    id
                }
            }
        }
    }
    """

    return execute(query)


@pytest.fixture
def update_archives(execute_update):
    mutation = """
    mutation updateArchives($ids: [Int!]!, $input: UpdateArchiveInput!) {
        updateArchives(ids: $ids, input: $input) {
            __typename
            ... on Success {
                message
            }
            ... on Error {
                message
            }
            ... on PageRemoteError {
                id
                archiveId
            }
            ... on IDNotFoundError {
                id
            }
        }
    }
    """

    return execute_update(mutation)


@pytest.fixture
def delete_archives(execute_delete):
    mutation = """
    mutation deleteArchives($ids: [Int!]!) {
        deleteArchives(ids: $ids) {
            __typename
            ... on Success {
                message
            }
            ... on Error {
                message
            }
            ... on IDNotFoundError {
                id
            }
        }
    }
    """

    return execute_delete(mutation)


def assert_image_matches(obj, model):
    assert obj["__typename"] == "Image"
    assert obj["id"] == model.id


def assert_page_matches(obj, model):
    assert obj["__typename"] == "Page"
    assert obj["id"] == model.id


@pytest.mark.anyio
async def test_query_archive(query_archive, gen_archive):
    archive = next(gen_archive)
    pages = archive.pages

    await DB.add(archive)

    response = Response(await query_archive(archive.id))
    response.assert_is("FullArchive")

    assert response.id == archive.id
    assert response.name == archive.name
    assert dt.fromisoformat(response.createdAt) == archive.created_at
    assert dt.fromisoformat(response.mtime) == archive.mtime
    assert response.size == archive.size
    assert response.path == archive.path
    assert response.comics == []
    assert response.pageCount == archive.page_count
    assert response.organized == archive.organized
    assert_image_matches(response.cover, pages[0].image)

    assert len(response.pages) == len(pages)

    page_iter = iter(sorted(pages, key=lambda page: page.index))
    for page in response.pages:
        matching_page = next(page_iter)
        assert_page_matches(page, matching_page)
        assert_image_matches(page["image"], matching_page.image)


@pytest.mark.anyio
async def test_query_archive_sorts_pages(query_archive, gen_jumbled_archive):
    archive = await DB.add(next(gen_jumbled_archive))

    response = Response(await query_archive(archive.id))
    response.assert_is("FullArchive")

    page_iter = iter(sorted(archive.pages, key=lambda page: page.index))
    for page in response.pages:
        matching_page = next(page_iter)
        assert_page_matches(page, matching_page)
        assert_image_matches(page["image"], matching_page.image)


@pytest.mark.anyio
async def test_query_archive_fails_not_found(query_archive):
    response = Response(await query_archive(1))
    response.assert_is("IDNotFoundError")
    assert response.id == 1
    assert response.message == "Archive ID not found: '1'"


@pytest.mark.anyio
async def test_query_archives(query_archives, gen_archive):
    archives = await DB.add_all(*gen_archive)

    response = Response(await query_archives())
    response.assert_is("ArchiveFilterResult")

    assert response.count == len(archives)
    assert isinstance((response.edges), list)
    assert len(response.edges) == len(archives)

    edges = iter(response.edges)
    for archive in sorted(archives, key=lambda a: a.name):
        edge = next(edges)
        assert edge["id"] == archive.id
        assert edge["name"] == archive.name
        assert edge["size"] == archive.size
        assert edge["pageCount"] == archive.page_count
        assert_image_matches(edge["cover"], archive.cover)


@pytest.fixture
def gen_archive_with_files(tmpdir, monkeypatch, gen_archive):
    content_dir = os.path.join(tmpdir, "content/")
    object_dir = os.path.join(tmpdir, "objects/")
    os.mkdir(content_dir)
    os.mkdir(object_dir)

    dirs = hircine.config.DirectoryStructure(scan=content_dir, objects=object_dir)
    monkeypatch.setattr(hircine.config, "dir_structure", dirs)

    archive = next(gen_archive)

    archive_path = Path(os.path.join(content_dir, "archive.zip"))
    archive_path.touch()
    archive.path = str(archive_path)

    img_paths = []
    for page in archive.pages:
        for suffix in ["full", "thumb"]:
            img_path = Path(thumb.object_path(object_dir, page.image.hash, suffix))
            os.makedirs(os.path.dirname(img_path), exist_ok=True)
            img_path.touch()

            img_paths.append(img_path)

    yield archive, content_dir, object_dir, img_paths


@pytest.mark.anyio
async def test_delete_archive(delete_archives, gen_archive_with_files):
    archive, content_dir, object_dir, img_paths = gen_archive_with_files
    archive_path = archive.path

    archive = await DB.add(archive)
    page_ids = [page.id for page in archive.pages]
    image_ids = [page.image.id for page in archive.pages]

    response = Response(await delete_archives(archive.id))
    response.assert_is("DeleteSuccess")

    archive = await DB.get(Archive, archive.id)
    assert archive is None

    async with database.session() as s:
        db_pages = (await s.scalars(select(Page).where(Page.id.in_(page_ids)))).all()
        db_images = (
            await s.scalars(select(Image).where(Image.id.in_(image_ids)))
        ).all()

    assert db_pages == []
    assert db_images == []

    assert os.path.exists(archive_path) is False
    for img_path in img_paths:
        assert os.path.exists(img_path) is False


@pytest.mark.anyio
async def test_delete_archive_deletes_images_only_when_necessary(
    delete_archives, gen_archive_with_files, gen_archive
):
    archive, content_dir, object_dir, img_paths = gen_archive_with_files
    archive_path = archive.path

    archive = await DB.add(archive)
    page_ids = [page.id for page in archive.pages]
    image_ids = [page.image.id for page in archive.pages]

    another = next(gen_archive)
    another.pages = [
        Page(path="foo", index=1, image_id=id, archive=another) for id in image_ids
    ]
    another.cover = archive.cover
    await DB.add(another)

    response = Response(await delete_archives(archive.id))
    response.assert_is("DeleteSuccess")

    archive = await DB.get(Archive, archive.id)
    assert archive is None

    async with database.session() as s:
        db_pages = (await s.scalars(select(Page).where(Page.id.in_(page_ids)))).all()
        db_images = (
            await s.scalars(select(Image.id).where(Image.id.in_(image_ids)))
        ).all()

    assert db_pages == []
    assert db_images == image_ids

    assert os.path.exists(archive_path) is False
    for img_path in img_paths:
        assert os.path.exists(img_path) is True


@pytest.mark.anyio
async def test_delete_archive_cascades_on_comic(
    delete_archives, gen_archive_with_files
):
    archive, *_ = gen_archive_with_files
    comic = Comic(
        id=1,
        title="Hic Sunt Dracones",
        archive=archive,
        cover=archive.cover,
        pages=archive.pages,
    )

    comic = await DB.add(comic)

    response = Response(await delete_archives(comic.archive.id))
    response.assert_is("DeleteSuccess")

    archive = await DB.get(Archive, archive.id)
    assert archive is None

    comic = await DB.get(Comic, comic.id)
    assert comic is None


@pytest.mark.anyio
async def test_update_archives(update_archives, gen_archive):
    old_archive = await DB.add(next(gen_archive))

    response = Response(
        await update_archives(
            old_archive.id,
            {"cover": {"id": old_archive.pages[1].id}, "organized": True},
        )
    )
    response.assert_is("UpdateSuccess")

    archive = await DB.get(Archive, old_archive.id)

    assert archive.cover_id == old_archive.pages[1].image.id
    assert archive.organized is True


@pytest.mark.anyio
async def test_update_archive_fails_archive_not_found(update_archives, gen_archive):
    archive = await DB.add(next(gen_archive))

    response = Response(
        await update_archives(100, {"cover": {"id": archive.pages[1].id}})
    )
    response.assert_is("IDNotFoundError")
    assert response.id == 100
    assert response.message == "Archive ID not found: '100'"


@pytest.mark.anyio
async def test_update_archive_cover_fails_page_not_found(update_archives, gen_archive):
    archive = await DB.add(next(gen_archive))

    response = Response(await update_archives(archive.id, {"cover": {"id": 100}}))
    response.assert_is("IDNotFoundError")
    assert response.id == 100
    assert response.message == "Page ID not found: '100'"


@pytest.mark.anyio
async def test_update_archive_cover_fails_page_remote(update_archives, gen_archive):
    archive = await DB.add(next(gen_archive))
    another = await DB.add(next(gen_archive))
    remote_id = another.pages[0].id

    response = Response(await update_archives(archive.id, {"cover": {"id": remote_id}}))
    response.assert_is("PageRemoteError")
    assert response.id == remote_id
    assert response.archiveId == another.id
    assert (
        response.message
        == f"Page ID {remote_id} comes from remote archive ID {another.id}"
    )