import json import threading import time from pathlib import Path import openpyxl def test_parser_deduplicates_and_reports_invalid_ids(app_mod): ids, duplicates, invalid = app_mod._parse_resolve_ids( '1, ILQ-2 ilq-2; ILQ-3\nbad-id, 4') assert ids == ['ILQ-1', 'ILQ-2', 'ILQ-3', 'ILQ-4'] assert duplicates == 1 assert invalid == ['bad-id'] def test_resolve_one_returns_full_question_content(app_mod, monkeypatch): payload = { 'data': { 'toc_mapping': {'grade': [12]}, 'question_type': 'single correct mcq', 'objective': 'objective-id', 'bloom_taxonomy': 'bloom-id', 'difficulty_level': 'difficulty-id', 'status': 'approved', 'question': { 'question_text': '

Choose the correct option.

', 'answer_options': [ {'data': '

First

', 'is_correct': False}, {'data': '

Second

', 'is_correct': True}, ], 'correct_answer': ['2'], 'solution': '

Explanation here.

', 'video_solution_id': 'video-9', 'child_questions': [{ 'question_id': 'ILQ-2', 'question_text': '

Child question.

', 'answer_options': [ {'data': '

Wrong

', 'is_correct': False}, {'data': '

Right

', 'is_correct': True}, ], 'correct_answer': ['2'], 'solution': '

Child solution.

', }], }, } } class Response: status_code = 200 def raise_for_status(self): return None def json(self): return payload monkeypatch.setattr(app_mod._TOC_HTTP, 'post', lambda *args, **kwargs: Response()) monkeypatch.setattr( app_mod, '_resolve_toc_names', lambda *args, **kwargs: { 'grade': 'Grade 12', 'subject': 'Physics', 'exam': 'JEE Main', 'chapter': 'Chapter', 'topic': 'Topic', 'subtopic': 'Subtopic'}) monkeypatch.setattr(app_mod, '_lookup_reverse', lambda *args, **kwargs: { 'objective-id': 'Theory', 'bloom-id': 'Application', 'difficulty-id': 'Moderate'}) row = app_mod._resolve_one('token', 'user', '123') assert row['question_id'] == 'ILQ-123' assert row['question_text'] == 'Choose the correct option.' assert row['options'] == ['First', 'Second'] assert row['options_text'] == '(A) First\n(B) Second' assert row['correct_answer'] == 'B' assert row['correct_answer_raw'] == ['2'] assert row['solution'] == 'Explanation here.' assert row['objective'] == 'Theory' assert row['bloom_taxonomy'] == 'Application' assert row['difficulty'] == 'Moderate' assert row['video_solution_id'] == 'video-9' assert row['child_questions'][0]['question_id'] == 'ILQ-2' assert 'Child solution.' in row['child_questions_text'] assert row['raw'] == payload['data'] def test_streaming_runner_preserves_order_and_builds_excel(app_mod, tmp_path, monkeypatch): root = tmp_path / 'resolve-jobs' job_id = 'job-1' job_dir = root / job_id job_dir.mkdir(parents=True) result_path = job_dir / 'results.jsonl' result_path.touch() monkeypatch.setattr(app_mod, 'RESOLVE_TOC_ROOT', root) monkeypatch.setattr(app_mod, 'RESOLVE_TOC_WORKERS', 4) monkeypatch.setattr(app_mod, 'log_usage', lambda *args, **kwargs: None) job = { 'job_id': job_id, 'owner': 'owner', 'status': 'queued', 'phase': 'queued', 'total': 5, 'done': 0, 'succeeded': 0, 'failed': 0, 'cancelled': 0, 'error': '', 'cancel_event': threading.Event(), 'result_path': str(result_path), 'xlsx_path': '', 'created_at': time.time(), 'updated_at': time.time(), } app_mod.RESOLVE_TOC_JOBS[job_id] = job def fake_resolve(token, uid, qid, nav_cache=None, children_cache=None, exam=None): number = int(qid.rsplit('-', 1)[1]) time.sleep((6 - number) * 0.003) return { 'question_id': qid, 'fetch_status': 'ok', 'error': '', 'question_text': f'Question {number}', 'options_text': f'(A) Option {number}', 'correct_answer': 'A', 'solution': f'Solution {number}', 'child_questions_text': '', 'raw': {'number': number}, } monkeypatch.setattr(app_mod, '_resolve_one', fake_resolve) try: app_mod._run_resolve_job( [f'ILQ-{number}' for number in range(1, 6)], 'token', 'user', job_id) rows = list(app_mod._iter_resolve_jsonl(result_path)) assert [row['question_id'] for row in rows] == [f'ILQ-{number}' for number in range(1, 6)] assert [row['input_index'] for row in rows] == [0, 1, 2, 3, 4] assert job['status'] == 'done' assert job['done'] == 5 assert job['succeeded'] == 5 assert Path(job['xlsx_path']).exists() workbook = openpyxl.load_workbook(job['xlsx_path'], read_only=True) assert sum(1 for _ in workbook['TOC Resolve'].iter_rows()) == 6 workbook.close() finally: app_mod.RESOLVE_TOC_JOBS.pop(job_id, None) def test_excel_stream_is_formula_safe_and_chunks_long_cells(app_mod, tmp_path): path = tmp_path / 'results.xlsx' long_text = 'x' * 30010 rows = [{ 'input_index': 0, 'question_id': 'ILQ-1', 'fetch_status': 'ok', 'question_text': '=1+1', 'raw': {'kept': True}, }, { 'input_index': 1, 'question_id': 'ILQ-2', 'question_text': long_text, }] app_mod._write_toc_xlsx(rows, path) workbook = openpyxl.load_workbook(path, read_only=False, data_only=False) sheet = workbook['TOC Resolve'] chunks = workbook['Text Chunks'] # Looked up by header, not by column letter: adding a column (Exam Match) must # not silently move what this test is checking. headers = {c.value: c.column for c in sheet[1]} question_col = headers['Question'] assert sheet.cell(row=2, column=question_col).value == "'=1+1" assert sheet.cell(row=2, column=question_col).data_type == 's' assert len(sheet.cell(row=3, column=question_col).value) == app_mod.TEXT_CHUNK_LIMIT assert 'Exam Match' in headers assert sum(1 for _ in chunks.iter_rows()) == 2 assert chunks['B2'].value == 'ILQ-2' assert chunks['C2'].value == 'question_text' assert chunks['E2'].value == 'x' * 10 workbook.close() def test_job_routes_are_summary_only_preview_bounded_and_owner_scoped( app_mod, tmp_path, monkeypatch): root = tmp_path / 'resolve-jobs' job_id = 'owner-job' job_dir = root / job_id job_dir.mkdir(parents=True) result_path = job_dir / 'results.jsonl' xlsx_path = job_dir / 'results.xlsx' long_question = 'q' * 5000 row = { 'input_index': 0, 'question_id': 'ILQ-77', 'fetch_status': 'ok', 'error': '', 'grade': 'Grade 12', 'subject': 'Physics', 'exam': 'JEE Main', 'toc_chain': 'JEE Main > Physics > Chapter', 'question_text': long_question, 'options_text': '(A) One', 'correct_answer': 'A', 'solution': 'Solution', 'child_questions_text': '', 'raw': {'id': 77}, } with result_path.open('w', encoding='utf-8') as handle: handle.write(json.dumps(row, ensure_ascii=False) + '\n') app_mod._write_toc_xlsx([row], xlsx_path) monkeypatch.setattr(app_mod, 'RESOLVE_TOC_ROOT', root) monkeypatch.setattr(app_mod, 'REQUIRE_PASSWORD', False) app_mod.RESOLVE_TOC_JOBS[job_id] = { 'job_id': job_id, 'owner': 'owner-1', 'status': 'done', 'phase': 'finished', 'total': 1, 'done': 1, 'succeeded': 1, 'failed': 0, 'cancelled': 0, 'error': '', 'cancel_event': threading.Event(), 'result_path': str(result_path), 'xlsx_path': str(xlsx_path), 'created_at': time.time(), 'updated_at': time.time(), } client = app_mod.app.test_client() with client.session_transaction() as flask_session: flask_session['tagger_cid'] = 'owner-1' try: status = client.get('/resolve_toc/status/' + job_id) assert status.status_code == 200 assert status.headers['Cache-Control'] == 'no-store' assert status.json['done'] == 1 assert status.json['downloads_ready'] is True assert 'results' not in status.json preview = client.get('/resolve_toc/preview/' + job_id + '?offset=0&limit=1') assert preview.status_code == 200 assert preview.json['rows'][0]['question_id'] == 'ILQ-77' assert len(preview.json['rows'][0]['question_text']) == 4001 jsonl = client.get('/resolve_toc/download/' + job_id + '/jsonl') assert jsonl.status_code == 200 assert json.loads(jsonl.get_data(as_text=True).strip())['question_id'] == 'ILQ-77' xlsx = client.get('/resolve_toc/download/' + job_id + '/xlsx') assert xlsx.status_code == 200 assert xlsx.get_data().startswith(b'PK') app_mod.RESOLVE_TOC_JOBS[job_id]['xlsx_path'] = '' building = client.get('/resolve_toc/download/' + job_id + '/xlsx') assert building.status_code == 409 app_mod.RESOLVE_TOC_JOBS[job_id]['xlsx_path'] = str(xlsx_path) other = app_mod.app.test_client() with other.session_transaction() as flask_session: flask_session['tagger_cid'] = 'owner-2' assert other.get('/resolve_toc/status/' + job_id).status_code == 404 assert other.get('/resolve_toc/download/' + job_id + '/jsonl').status_code == 404 finally: app_mod.RESOLVE_TOC_JOBS.pop(job_id, None) def _bulk_job(app_mod, tmp_path, monkeypatch, job_id, total, workers=2): root = tmp_path / 'resolve-jobs' job_dir = root / job_id job_dir.mkdir(parents=True) result_path = job_dir / 'results.jsonl' result_path.touch() monkeypatch.setattr(app_mod, 'RESOLVE_TOC_ROOT', root) monkeypatch.setattr(app_mod, 'RESOLVE_TOC_WORKERS', workers) monkeypatch.setattr(app_mod, 'log_usage', lambda *args, **kwargs: None) job = { 'job_id': job_id, 'owner': 'owner', 'status': 'queued', 'phase': 'queued', 'total': total, 'done': 0, 'succeeded': 0, 'failed': 0, 'cancelled': 0, 'error': '', 'cancel_event': threading.Event(), 'result_path': str(result_path), 'xlsx_path': '', 'created_at': time.time(), 'updated_at': time.time(), } app_mod.RESOLVE_TOC_JOBS[job_id] = job return job, result_path def _ok_row(qid): return {'question_id': qid, 'fetch_status': 'ok', 'error': ''} def test_expired_token_mid_run_still_builds_excel(app_mod, tmp_path, monkeypatch): """An 18k run that loses its CMS session partway must still hand back an Excel of what it finished, not just the JSONL.""" ids = [f'ILQ-{n}' for n in range(1, 21)] job, result_path = _bulk_job(app_mod, tmp_path, monkeypatch, 'expired-job', len(ids)) def fake_resolve(token, uid, qid, nav_cache=None, children_cache=None, exam=None): if qid == 'ILQ-8': raise app_mod.CommAuthError(app_mod.COMM_EXPIRED_MSG) return _ok_row(qid) monkeypatch.setattr(app_mod, '_resolve_one', fake_resolve) try: app_mod._run_resolve_job(ids, 'token', 'user', 'expired-job') rows = list(app_mod._iter_resolve_jsonl(result_path)) assert [row['question_id'] for row in rows] == ids assert all(row['fetch_status'] == 'ok' for row in rows[:7]) assert job['status'] == 'error' assert job['error'] == app_mod.COMM_EXPIRED_MSG assert Path(job['xlsx_path']).exists() workbook = openpyxl.load_workbook(job['xlsx_path'], read_only=True) assert sum(1 for _ in workbook['TOC Resolve'].iter_rows()) == len(ids) + 1 workbook.close() finally: app_mod.RESOLVE_TOC_JOBS.pop('expired-job', None) def test_cancelled_run_still_builds_excel(app_mod, tmp_path, monkeypatch): ids = [f'ILQ-{n}' for n in range(1, 11)] job, _ = _bulk_job(app_mod, tmp_path, monkeypatch, 'cancel-job', len(ids)) def fake_resolve(token, uid, qid, nav_cache=None, children_cache=None, exam=None): if qid == 'ILQ-3': job['cancel_event'].set() return _ok_row(qid) monkeypatch.setattr(app_mod, '_resolve_one', fake_resolve) try: app_mod._run_resolve_job(ids, 'token', 'user', 'cancel-job') assert job['status'] == 'cancelled' assert job['done'] == len(ids) assert Path(job['xlsx_path']).exists() finally: app_mod.RESOLVE_TOC_JOBS.pop('cancel-job', None) def test_one_stuck_question_does_not_stall_the_rest(app_mod, tmp_path, monkeypatch): """Row 1 blocks until row 30 has been started. With the old 2x-workers in-order window, row 30 could never start while row 1 was pending.""" ids = [f'ILQ-{n}' for n in range(1, 41)] job, result_path = _bulk_job(app_mod, tmp_path, monkeypatch, 'stall-job', len(ids)) later_started = threading.Event() def fake_resolve(token, uid, qid, nav_cache=None, children_cache=None, exam=None): if qid == 'ILQ-30': later_started.set() if qid == 'ILQ-1': later_started.wait(timeout=5) return _ok_row(qid) monkeypatch.setattr(app_mod, '_resolve_one', fake_resolve) try: app_mod._run_resolve_job(ids, 'token', 'user', 'stall-job') assert later_started.is_set() rows = list(app_mod._iter_resolve_jsonl(result_path)) assert [row['question_id'] for row in rows] == ids assert job['status'] == 'done' finally: app_mod.RESOLVE_TOC_JOBS.pop('stall-job', None)