Newer
Older
TIASDataHub / tests / catalog / test_queries.py
"""目録の集計."""

import sqlite3

from tiasdata import catalog


def test_count_kinds_after_initial_migration(catalog_conn: sqlite3.Connection) -> None:
    # SPEC_02「kinds」: 最初に用意する種類は asset 4 件・annotation 1 件.0002 で review を,
    # 0003 で deeptias_features を,0004 で deeptias_output_file・tongue_color_rounds を,
    # 0005 で tongue_color_first_round を,0006 で tongue_seg_image・tongue_seg を足した
    assert catalog.count_kinds(catalog_conn) == {"annotation": 6, "asset": 6}


def _insert_unlinked(conn: sqlite3.Connection, seed: str, kind: str) -> None:
    conn.execute(
        "INSERT INTO assets (sha256, kind, capture_id, ext, size_bytes, source, source_name,"
        " registered_at) VALUES (?, ?, NULL, 'png', 1, 's', 'n', '2026-11-01T00:00:00Z')",
        (seed * 64, kind),
    )


def test_count_assets_without_capture_excludes_given_kinds(
    catalog_conn: sqlite3.Connection,
) -> None:
    _insert_unlinked(catalog_conn, "a", "tongue_crop_masked")
    _insert_unlinked(catalog_conn, "b", "deeptias_output_file")
    _insert_unlinked(catalog_conn, "c", "deeptias_output_file")
    assert catalog.count_assets_without_capture(catalog_conn) == 3
    assert (
        catalog.count_assets_without_capture(catalog_conn, exclude_kinds=["deeptias_output_file"])
        == 1
    )


def _capture(conn: sqlite3.Connection, capture_id: str, subject_id: str | None) -> None:
    if subject_id is not None:
        conn.execute(
            "INSERT OR IGNORE INTO subjects (subject_id, created_at)"
            " VALUES (?, '2026-11-01T00:00:00Z')",
            (subject_id,),
        )
    conn.execute(
        "INSERT INTO captures (capture_id, subject_id) VALUES (?, ?)", (capture_id, subject_id)
    )


def test_captures_without_subject_are_counted_apart(catalog_conn: sqlite3.Connection) -> None:
    # catalog/0006: 症例の無い撮影は数え,撮影が 2 つ以上の症例には数えない
    assert catalog.count_captures_without_subject(catalog_conn) == 0
    _capture(catalog_conn, "C000001", "S000001")
    _capture(catalog_conn, "C000002", "S000001")
    _capture(catalog_conn, "C000003", "S000002")
    for n in range(4, 7):
        _capture(catalog_conn, f"C{n:06d}", None)
    assert catalog.count_captures(catalog_conn) == 6
    assert catalog.count_captures_without_subject(catalog_conn) == 3
    assert catalog.count_subjects(catalog_conn) == 2
    assert catalog.count_subjects_with_multiple_captures(catalog_conn) == 1


def test_only_captures_without_subject_are_not_a_subject_with_multiple_captures(
    catalog_conn: sqlite3.Connection,
) -> None:
    _capture(catalog_conn, "C000001", None)
    _capture(catalog_conn, "C000002", None)
    assert catalog.count_subjects_with_multiple_captures(catalog_conn) == 0
    assert catalog.count_captures_without_subject(catalog_conn) == 2