File size: 14,222 Bytes
5b082d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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 '<math' in html and '$' not in html
    assert '<mi>F</mi>' in html and '<mi>m</mi>' in html


def test_display_math_across_lines_converts(app_mod):
    html = app_mod.solution_text_to_html('So $$\nE = mc^2\n$$.')
    assert '<math' in html and '$' not in html
    assert '<msup>' 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('<math') == 2 and '$' not in html


def test_prose_newlines_still_make_paragraphs(app_mod):
    html = app_mod.solution_text_to_html('Step one.\n\nStep two $x = 2$.')
    assert html.count('<p>') == 2
    assert 'Step one.' in html and 'Step two' in html
    assert '<math' in html


def test_plain_math_without_dollars_stays_plain(app_mod):
    html = app_mod.solution_text_to_html('s = ut + 1/2 at^2')
    assert '<math' not in html and html == '<p>s = ut + 1/2 at^2</p>'


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 '<math' in html
    assert '&amp;' in html and '&lt;' in html
    assert '<mi>F</mi>' in html


# ── boxed final answers render as a real box ──────────────────────────────────
# latex2mathml maps \\boxed{...} to <menclose notation="box">, 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 '<menclose' not in html                     # not the Chrome-invisible form
    assert 'border:1.4px solid' in html                # a box the browser draws
    assert '<mn>0</mn>' in html                        # content kept
    assert '<math' in html

def test_boxed_answer_missing_the_dollar_is_plain(app_mod):
    html = app_mod.solution_text_to_html('Answer: \\boxed{x = 3}')
    assert '<menclose' not in html and 'border:' not in html

def test_boxed_within_frac_still_boxes_the_whole_math(app_mod):
    html = app_mod.solution_text_to_html('$\\frac{1}{2}\\boxed{20}$ J')
    assert 'border:1.4px solid' in html and '<mn>20</mn>' in html
    assert '<menclose' not in html


# ── pdf_reader truncation ────────────────────────────────────────────────────
def test_truncate_for_prompt_cuts_on_page_boundary():
    import pdf_reader
    pages = ['a' * 50, 'b' * 50, 'c' * 50]
    text, truncated = pdf_reader.truncate_for_prompt(pages, cap=120)
    assert text == 'a' * 50 + '\n' + 'b' * 50   # whole pages only
    assert truncated is True
    assert 'c' not in text


def test_truncate_for_prompt_single_oversized_page_is_sliced():
    import pdf_reader
    pages = ['x' * 200]
    text, truncated = pdf_reader.truncate_for_prompt(pages, cap=100)
    assert len(text) == 100 and set(text) == {'x'}
    assert truncated is True


def test_truncate_for_prompt_no_cut_needed():
    import pdf_reader
    pages = ['hello', 'world']
    text, truncated = pdf_reader.truncate_for_prompt(pages, cap=1000)
    assert text == 'hello\nworld'
    assert truncated is False