"""The write-existing-solution paths of /solutions. Three source modes share ONE review/push engine: the rows they hand to the review table must be identical in shape, so a pilot that uses the PDF path or the direct-paste path cannot fall over later at push time. Covered here: * build_prompt gains a SOURCE-SOLUTIONS PDF mode (it must NOT tell the AI to solve from scratch, and must carry the source text + order hint). * rows_from_pasted_text maps QID-prefixed AND numbered blocks onto the fetched records, pulls out an optional "Answer:" line, and reports orphans as warnings rather than crashing. * pdf_reader.truncate_for_prompt cuts on a page boundary. """ import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'backend')) @pytest.fixture(scope='module') def sa(): import solution_assist return solution_assist def recs(): """The shape ai_assist.fetch_contents() actually returns.""" return { 'ILQ-1': {'question_id': 'ILQ-1', 'question_type': 'single correct mcq', 'question_text': 'What is 2+2?', 'options': ['3', '4', '5', '6'], 'correct': 'B', 'is_matrix': False, 'is_passage': False}, 'ILQ-2': {'question_id': 'ILQ-2', 'question_type': 'single correct mcq', 'question_text': 'What is 3*3?', 'options': ['6', '8', '9', '12'], 'correct': 'C', 'is_matrix': False, 'is_passage': False}, } # ── build_prompt: the two modes must not read alike ────────────────────────── def test_pdf_prompt_carries_source_and_no_solve_from_scratch(sa): contents = list(recs().values()) p = sa.build_prompt(contents, pdf_docs=['Q1. Add the numbers: 2+2=4. Answer B'], alignment='order') assert 'SOURCE SOLUTIONS' in p assert '2+2=4' in p # the existing-solution mode must not ask the AI to work it out itself assert 'solve from scratch' not in p.lower().replace('do not solve', '') assert 'same order' in p.lower() # both QIDs still present so the reply maps back by qid assert 'ILQ-1' in p and 'ILQ-2' in p def test_pdf_prompt_auto_alignment_warns_order_unknown(sa): p = sa.build_prompt(list(recs().values()), pdf_docs=['raw source'], alignment='auto') assert 'not guaranteed to be in the same order' in p.lower() assert 'the solutions are numbered in the same order' not in p.lower() def test_default_prompt_has_no_source_section(sa): p = sa.build_prompt(list(recs().values())) assert 'SOURCE SOLUTIONS' not in p assert 'Work each question out yourself' in p # ── rows_from_pasted_text: QID-prefixed blocks ─────────────────────────────── def test_qid_prefixed_blocks_map_themselves(sa): text = ('ILQ-1 Apply 2+2=4.\nStep 1: add\nAnswer: B\n\n' 'ILQ-2 Multiply 3*3=9.\nAnswer: C') rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) by_id = {r['question_id']: r for r in rows} assert set(by_id) == {'ILQ-1', 'ILQ-2'} assert by_id['ILQ-1']['push_solution'] is True assert by_id['ILQ-1']['ai_answer'] == 'B' # stored B + pasted B -> MATCH, so the key is pre-ticked assert by_id['ILQ-1']['verdict'] == 'MATCH' assert by_id['ILQ-1']['push_key'] is True # the Answer line is stripped out of the solution text assert 'Answer: B' not in by_id['ILQ-1']['solution'] assert not warns def test_numbered_blocks_align_to_qid_order(sa): text = ('1. 2+2=4\nAnswer: B\n\n' '2. 3*3=9\nAnswer: C') rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) ordered = sorted(rows, key=lambda r: r['question_id']) assert [r['question_id'] for r in ordered] == ['ILQ-1', 'ILQ-2'] assert not warns def test_unknown_qid_is_warning_not_crash(sa): text = 'ILQ-999 Some solution\nAnswer: A' with pytest.raises(ValueError) as ei: sa.rows_from_pasted_text(text, list(recs().values())) # the error names the offending QID so the SME can fix the paste assert 'ILQ-999' in str(ei.value) def test_extra_numbered_block_beyond_fetch_warns(sa): text = '1. sol\n2. sol2\n3. sol3' rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) assert len(rows) == 2 assert any('beyond' in w for w in warns) def test_numbered_lines_inside_a_qid_block_stay_as_solution(sa): # With a QID present, numbered lines must NOT start new blocks — they are # step numbers / stray question numbers inside the solution text. text = ('ILQ-1 Step 0: given\n' '1. add\n' '12. 2+2=4\n' 'Answer: B') rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) assert len(rows) == 1 # one block, not three assert rows[0]['question_id'] == 'ILQ-1' assert '1. add' in rows[0]['solution'] # numbered lines preserved assert '12. 2+2=4' in rows[0]['solution'] assert 'Answer: B' not in rows[0]['solution'] # answer line still consumed assert rows[0]['ai_answer'] == 'B' assert rows[0]['verdict'] == 'MATCH' # the only warning is the honest ILQ-2-never-got-a-block one (not a # misparsed-number complaint) assert not any('question number' in w or w.startswith('block 2') for w in warns) def test_qid_block_whose_first_numbered_line_is_a_marker_is_stripped(sa): # A plain numbered list with NO QID anywhere still aligns by order (1,2,3…). text = '1. 2+2=4\n\n2. 3*3=9' rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) ordered = sorted(rows, key=lambda r: r['question_id']) assert [r['question_id'] for r in ordered] == ['ILQ-1', 'ILQ-2'] assert ordered[0]['solution'] == '2+2=4' # leading '1.' dropped assert not warns def test_non_sequential_number_in_numbered_mode_does_not_split(sa): # Without QIDs, only a continuing 1,2,3… sequence splits — a stray '5.' that # follows a '1.' block is MANGLE, not a new question, so it stays on the block. text = '1. first solution\n\n5. stray numbered line' rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) assert len(rows) == 1 assert '5. stray numbered line' in rows[0]['solution'] def test_numbered_marker_never_leaks_into_the_solution(sa): # The SME pastes '1. [solution]' blocks with NO QIDs. The leading number # (question number) must never survive into the stored solution — whether it # is glued ('1.Apply'), spaced ('1. Apply'), a lone '1.' line, or a Q prefix. cases = [ ('1.Apply F = ma\n\n2.Use s = ut', ['Apply F = ma', 'Use s = ut']), ('1. Apply F = ma\n\n2. Use s = ut', ['Apply F = ma', 'Use s = ut']), ('1.\nApply F = ma\n\n2.\nUse s = ut', ['Apply F = ma', 'Use s = ut']), ('Q1. Apply F = ma\n\nQ2. Use s = ut', ['Apply F = ma', 'Use s = ut']), ] for text, expected in cases: rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) ordered = sorted(rows, key=lambda r: r['question_id']) assert [r['question_id'] for r in ordered] == ['ILQ-1', 'ILQ-2'] got = [r['solution'] for r in ordered] assert got == expected, (text, got) assert not warns, (text, warns) def test_latex_item_question_number_marker_is_stripped(sa): # Solutions pasted from .tex sources often carry their question number as a # LaTeX marker: '\begin{itemize}\item[5.] solution…\end{itemize}'. Both the # item number (the question number, which must not survive) and the itemize # scaffolding must be dropped from the stored solution. cases = [ (r'\begin{itemize}\item[5.] Apply F = ma' + '\n' + r'v = 5 + 2(3)' + '\n' + r'\end{itemize}' + '\n' + r'\begin{itemize}\item[6.] Use s = ut' + '\n' + r's = 10' + '\n' + r'\end{itemize}', ['Apply F = ma\nv = 5 + 2(3)', 'Use s = ut\ns = 10']), (r'\begin{itemize}' + '\n' + r'\item[5.]' + '\n' + r'Apply F = ma' + '\n' + r'\end{itemize}' + '\n' + r'\begin{itemize}' + '\n' + r'\item[6.]' + '\n' + r'Use s = ut' + '\n' + r'\end{itemize}', ['Apply F = ma', 'Use s = ut']), (r'\item[5]Apply F = ma' + '\n\n' + r'\item[6]Use s = ut', ['Apply F = ma', 'Use s = ut']), (r'\item[5.]Apply F = ma' + '\n\n' + r'\item[6.]Use s = ut', ['Apply F = ma', 'Use s = ut']), ] for text, expected in cases: rows, warns = sa.rows_from_pasted_text(text, list(recs().values())) ordered = sorted(rows, key=lambda r: r['question_id']) assert [r['question_id'] for r in ordered] == ['ILQ-1', 'ILQ-2'] got = [r['solution'] for r in ordered] assert got == expected, (text, got) assert not warns, (text, warns) assert all('\\item' not in s and 'itemize' not in s for s in got) def test_no_answer_line_means_no_key_writing(sa): text = 'ILQ-1 Just the working, no answer line.' rows, _ = sa.rows_from_pasted_text(text, list(recs().values())) r = rows[0] assert r['push_solution'] is True assert r['ai_answer'] == '(none)' assert r['can_key'] is False # nothing to write assert r['push_key'] is False def test_pasted_answer_disagreeing_with_key_is_mismatch_unticked(sa): text = 'ILQ-1 working\nAnswer: C' # stored key is B rows, _ = sa.rows_from_pasted_text(text, list(recs().values())) r = rows[0] assert r['verdict'] == 'MISMATCH' assert r['can_key'] is True assert r['push_key'] is False # SME must tick a MISMATCH deliberately def test_empty_paste_raises_readable_error(sa): with pytest.raises(ValueError): sa.rows_from_pasted_text('', list(recs().values())) # ── solution HTML: math must survive line breaks ───────────────────────────── # The pasted/PDF path is the first one where a human types the solution, and a # worked solution often wraps a $...$ across lines. solution_text_to_html used to # split the text into lines BEFORE converting math, so a split-on-next-line # formula was stored on the CMS as the literal text "$F =" instead of MathML — # what the SME saw as "raw LaTeX on the CMS". def test_math_wrapping_across_lines_converts(app_mod): html = app_mod.solution_text_to_html('Apply $F =\nma$ to get acceleration.') assert 'F' in html and 'm' in html def test_display_math_across_lines_converts(app_mod): html = app_mod.solution_text_to_html('So $$\nE = mc^2\n$$.') assert '' in html def test_multiple_line_wrapped_equations_in_one_solution(app_mod): html = app_mod.solution_text_to_html( 'Then $v^2 =\nu^2 +\n2as$ gives v. Finally $x =\ny$ works.') assert html.count('') == 2 assert 'Step one.' in html and 'Step two' in html assert 's = ut + 1/2 at^2

' def test_escape_and_math_share_one_line(app_mod): html = app_mod.solution_text_to_html( 'Note x & y goes here: $F = ma$; a plain < 10 is escaped.') assert 'F' in html # ── boxed final answers render as a real box ────────────────────────────────── # latex2mathml maps \\boxed{...} to , which is NOT in # MathML Core — Chrome/Edge (the CMS editor AND this review table) render the # content but silently drop the box. The box answer writing would LOOK boxed in # the source but be plain on the CMS. box_mathml_for_browser replaces the # menclose with a CSS-bordered span, which every browser draws. def test_boxed_answer_renders_a_real_box(app_mod): html = app_mod.solution_text_to_html('Hence the answer is $\\boxed{0}$.') assert '0' in html # content kept assert '20' in html assert '