Spaces:
Build error

trackademi / tests /test_materials_resolver.py
anwarKXC
feat: add tests for unit resolution and topic prioritization in materials resolver
71e4f47
Raw History Blame Contribute Delete
11.5 kB
import asyncio
from app.services.materials_resolver import MaterialFilter, MaterialScope, resolve_materials_to_page_filters
class _StubRow:
def __init__(self, **kwargs):
self._mapping = kwargs
class _StubResult:
def __init__(self, rows):
self._rows = rows
def __iter__(self):
return iter(self._rows)
def first(self):
return self._rows[0] if self._rows else None
class _StubSession:
"""Returns canned rows keyed by which SQL statement is executed โ€”
distinguishes the rag_documents page_count lookup from the rag_chunks
grouping query by checking for 'page_count' vs 'GROUP BY' in the SQL text."""
def __init__(self, page_count: int, chunk_rows: list[dict]):
self._page_count = page_count
self._chunk_rows = chunk_rows
async def execute(self, stmt, params=None):
sql = str(stmt)
if "page_count" in sql:
return _StubResult([_StubRow(page_count=self._page_count)])
return _StubResult([_StubRow(**r) for r in self._chunk_rows])
def test_whole_document_material_resolves_to_full_page_range():
materials = [MaterialFilter(document_id="doc1", scope=None)]
session = _StubSession(page_count=100, chunk_rows=[])
result = asyncio.run(resolve_materials_to_page_filters(materials, session=session))
assert result == [{"document_id": "doc1", "first_page": 1, "last_page": 100}]
def test_lesson_scoped_material_resolves_to_lesson_page_range():
materials = [
MaterialFilter(
document_id="doc1",
scope=MaterialScope(lesson_ids=["lesson:doc1:12"]),
)
]
session = _StubSession(
page_count=50,
chunk_rows=[
{"unit_title": None, "section_title": "Forces", "first_page": 12, "chunk_count": 8},
{"unit_title": None, "section_title": "Motion", "first_page": 19, "chunk_count": 5},
],
)
result = asyncio.run(resolve_materials_to_page_filters(materials, session=session))
assert result == [{"document_id": "doc1", "first_page": 12, "last_page": 18}]
def test_unresolvable_id_is_skipped_not_errored():
materials = [
MaterialFilter(
document_id="doc1",
scope=MaterialScope(lesson_ids=["lesson:doc1:999"]),
)
]
session = _StubSession(
page_count=50,
chunk_rows=[
{"unit_title": None, "section_title": "Forces", "first_page": 12, "chunk_count": 8},
],
)
result = asyncio.run(resolve_materials_to_page_filters(materials, session=session))
assert result == []
# โ”€โ”€ Topic-level scoping (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def test_topic_slugs_resolve_to_their_page_span_with_one_page_margin():
"""The narrowest scope, and the one that matters: a poet recurs all through
a book, so "generate from ู…ุฏุฑุณุฉ ุฃุจูˆู„ูˆ" must mean the pages where the book
teaches it โ€” not every page that mentions the name."""
import asyncio
from app.models.schemas import MaterialFilter, MaterialScope
from app.services.materials_resolver import (
_TOPIC_PAGE_MARGIN, resolve_materials_to_page_filters,
)
doc = "11111111-1111-1111-1111-111111111111"
class _Row:
def __init__(self, m):
self._mapping = m
class _Res(list):
def first(self):
return self[0] if self else None
class _Session:
async def execute(self, statement, params=None):
sql = str(statement)
if "page_count" in sql:
return _Res([_Row({"page_count": 232})])
if "FROM rag_topics" in sql:
assert params["slugs"] == ["ู…ุฏุฑุณุฉ-ุฃุจูˆู„ูˆ"]
return _Res([_Row({"first_page": 69, "last_page": 71})])
raise AssertionError(f"unexpected: {sql[:80]}")
filters = asyncio.run(resolve_materials_to_page_filters(
[MaterialFilter(document_id=doc,
scope=MaterialScope(topic_slugs=["ู…ุฏุฑุณุฉ-ุฃุจูˆู„ูˆ"]))],
session=_Session(),
))
assert filters == [{
"document_id": doc,
"first_page": 69 - _TOPIC_PAGE_MARGIN,
"last_page": 71 + _TOPIC_PAGE_MARGIN,
}]
def test_the_margin_never_runs_off_either_end_of_the_book():
import asyncio
from app.models.schemas import MaterialFilter, MaterialScope
from app.services.materials_resolver import resolve_materials_to_page_filters
doc = "22222222-2222-2222-2222-222222222222"
class _Row:
def __init__(self, m):
self._mapping = m
class _Res(list):
def first(self):
return self[0] if self else None
class _Session:
async def execute(self, statement, params=None):
if "page_count" in str(statement):
return _Res([_Row({"page_count": 10})])
return _Res([_Row({"first_page": 1, "last_page": 10})])
filters = asyncio.run(resolve_materials_to_page_filters(
[MaterialFilter(document_id=doc, scope=MaterialScope(topic_slugs=["s"]))],
session=_Session(),
))
assert filters == [{"document_id": doc, "first_page": 1, "last_page": 10}]
def test_a_selected_topic_is_never_widened_back_to_its_lesson():
"""Page filters are OR-ed, so emitting the parent lesson beside a topic
inside it cancels the narrowing entirely โ€” the teacher asks for one story
and gets the whole prose chapter."""
import asyncio
from app.models.schemas import MaterialFilter, MaterialScope
from app.services.materials_resolver import resolve_materials_to_page_filters
doc = "33333333-3333-3333-3333-333333333333"
class _Row:
def __init__(self, m):
self._mapping = m
class _Res(list):
def first(self):
return self[0] if self else None
class _Session:
async def execute(self, statement, params=None):
sql = str(statement)
if "page_count" in sql:
return _Res([_Row({"page_count": 232})])
if "FROM rag_topics" in sql:
return _Res([_Row({"first_page": 128, "last_page": 133})])
# units tree: one lesson spanning the whole prose chapter
return _Res([_Row({
"unit_title": None, "section_title": "ุงู„ู‚ุตุฉ ุงู„ู‚ุตูŠุฑุฉ",
"first_page": 126, "chunk_count": 19,
})])
filters = asyncio.run(resolve_materials_to_page_filters(
[MaterialFilter(document_id=doc, scope=MaterialScope(
lesson_ids=[f"lesson:{doc}:126"], topic_slugs=["ู‚ุตุฉ-ุงู„ูƒู†ูŠุณุฉ-ู†ูˆุฑุช"],
))],
session=_Session(),
))
assert filters == [{"document_id": doc, "first_page": 127, "last_page": 134}]
def test_a_lesson_in_a_different_subtree_still_resolves():
"""Narrowest-wins applies within a subtree, not globally: lesson A plus a
topic from lesson C legitimately means both."""
import asyncio
from app.models.schemas import MaterialFilter, MaterialScope
from app.services.materials_resolver import resolve_materials_to_page_filters
doc = "44444444-4444-4444-4444-444444444444"
class _Row:
def __init__(self, m):
self._mapping = m
class _Res(list):
def first(self):
return self[0] if self else None
class _Session:
async def execute(self, statement, params=None):
sql = str(statement)
if "page_count" in sql:
return _Res([_Row({"page_count": 200})])
if "FROM rag_topics" in sql:
return _Res([_Row({"first_page": 128, "last_page": 133})])
return _Res([
_Row({"unit_title": None, "section_title": "ุฏุฑุณ ุฃ",
"first_page": 7, "chunk_count": 5}),
_Row({"unit_title": None, "section_title": "ุงู„ู‚ุตุฉ ุงู„ู‚ุตูŠุฑุฉ",
"first_page": 126, "chunk_count": 19}),
])
filters = asyncio.run(resolve_materials_to_page_filters(
[MaterialFilter(document_id=doc, scope=MaterialScope(
lesson_ids=[f"lesson:{doc}:7"], topic_slugs=["ู‚ุตุฉ-ุงู„ูƒู†ูŠุณุฉ-ู†ูˆุฑุช"],
))],
session=_Session(),
))
spans = sorted((f["first_page"], f["last_page"]) for f in filters)
assert spans == [(7, 125), (127, 134)], spans
def test_a_unit_with_no_lessons_resolves_to_its_page_span():
"""Every grammar unit in the Sec3 Arabic book has topics but no lessons.
Until the wizard could emit unitIds these were unreachable, and the
resolver's own query used to filter them out before the tree was built."""
import asyncio
from app.models.schemas import MaterialFilter, MaterialScope
from app.services.materials_resolver import resolve_materials_to_page_filters
doc = "55555555-5555-5555-5555-555555555555"
class _Row:
def __init__(self, m):
self._mapping = m
class _Res(list):
def first(self):
return self[0] if self else None
class _Session:
async def execute(self, statement, params=None):
if "page_count" in str(statement):
return _Res([_Row({"page_count": 232})])
return _Res([
_Row({"unit_title": "ุงู„ูˆุญุฏุฉ ุงู„ุฃูˆู„ู‰", "section_title": None,
"first_page": 150, "chunk_count": 6}),
_Row({"unit_title": "ุงู„ูˆุญุฏู‡ ุงู„ุซุงู†ูŠู‡", "section_title": None,
"first_page": 157, "chunk_count": 7}),
])
filters = asyncio.run(resolve_materials_to_page_filters(
[MaterialFilter(document_id=doc,
scope=MaterialScope(unit_ids=[f"unit:{doc}:150"]))],
session=_Session(),
))
assert filters == [{"document_id": doc, "first_page": 150, "last_page": 156}]
def test_a_topic_inside_a_selected_unit_still_wins():
"""Narrowest-wins has to hold for units too, not just lessons."""
import asyncio
from app.models.schemas import MaterialFilter, MaterialScope
from app.services.materials_resolver import resolve_materials_to_page_filters
doc = "66666666-6666-6666-6666-666666666666"
class _Row:
def __init__(self, m):
self._mapping = m
class _Res(list):
def first(self):
return self[0] if self else None
class _Session:
async def execute(self, statement, params=None):
sql = str(statement)
if "page_count" in sql:
return _Res([_Row({"page_count": 232})])
if "FROM rag_topics" in sql:
return _Res([_Row({"first_page": 151, "last_page": 152})])
return _Res([
_Row({"unit_title": "ุงู„ูˆุญุฏุฉ ุงู„ุฃูˆู„ู‰", "section_title": None,
"first_page": 150, "chunk_count": 6}),
_Row({"unit_title": "ุงู„ูˆุญุฏู‡ ุงู„ุซุงู†ูŠู‡", "section_title": None,
"first_page": 157, "chunk_count": 7}),
])
filters = asyncio.run(resolve_materials_to_page_filters(
[MaterialFilter(document_id=doc, scope=MaterialScope(
unit_ids=[f"unit:{doc}:150"], topic_slugs=["ุงู„ุฃู…ุซุงู„-ุงู„ุนุฑุจูŠุฉ"],
))],
session=_Session(),
))
assert filters == [{"document_id": doc, "first_page": 150, "last_page": 153}]