import sys import threading import unittest from pathlib import Path from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) from nao_agent_task import TaskUnavailable, bind_task, normalize_task, plan_task from nao_metric_request import frozen_metric_frame from nao_quality_tools import QualityToolError, QualityTools, normalize_period from nao_query_contract import bind_query from test_nao_agent_task import task_value class MonthRangeTaskTests(unittest.TestCase): def test_range_survives_condition_changes_and_exact_query_binding(self): period = {'year': 2026, 'monthStart': 3, 'monthEnd': 5} context = {'_protocol': {'version': 1}, 'releaseId': 'fixed'} original = normalize_task(task_value(kind='metrics', dimensions=[], stages=[], fields=['rate'], period=period, trendRequired=True, filterUpdates={'extraFilters': {'customerCode': ['800001']}}), '客户三至五月趋势', context) inherited = bind_task(context, original) updated = normalize_task(task_value(kind='metrics', dimensions=[], stages=[], fields=['rate'], trendRequired=True, filterUpdates={'extraFilters': None}), '取消客户,期间不变', inherited) self.assertEqual(updated['period'], period) self.assertNotIn('extraFilters', updated['filters']) self.assertEqual(frozen_metric_frame(bind_task(context, updated))['period'], period) contract = {'task': updated, 'releaseId': 'fixed'} self.assertEqual(bind_query({'mode': 'query'}, contract)['period'], period) for wrong in ({'year': 2026}, {'year': 2026, 'month': 5}, {'year': 2026, 'monthStart': 1, 'monthEnd': 5}): with self.assertRaises(ValueError): bind_query({'mode': 'query', 'period': wrong}, contract) def test_invalid_ranges_are_rejected_by_planner_and_tools(self): for period in ({'year': 2026, 'monthStart': 1}, {'year': 2026, 'monthEnd': 9}, {'year': 2026, 'monthStart': 9, 'monthEnd': 1}, {'year': 2026, 'monthStart': True, 'monthEnd': 9}, {'year': 2026, 'monthStart': 1, 'monthEnd': 13}, {'year': 2026, 'monthStart': 1, 'monthEnd': 9, 'month': 9}, {'year': 2026, 'monthStart': 1, 'monthEnd': 9, 'quarter': 3}): with self.subTest(period=period): with self.assertRaises(TaskUnavailable): normalize_task(task_value(period=period), '月度趋势', {}) with self.assertRaises(QualityToolError): normalize_period(period) def test_metric_receipt_cannot_omit_or_expand_month_range(self): period = {'year': 2026, 'monthStart': 1, 'monthEnd': 9} response = {'summary': {}, 'coverage': {'rawRows': 1, 'includedRows': 1}, 'release': {'id': 'fixed'}, 'context': {**period, 'view': 'overall', 'includeUnassigned': False}} QualityTools._validate_source_snapshot(response, 'fixed', period, {}, 'overall') for changed in ({'year': 2026, 'view': 'overall'}, {**period, 'monthEnd': 12, 'view': 'overall'}): with self.assertRaises(QualityToolError): QualityTools._validate_source_snapshot({**response, 'context': changed}, 'fixed', period, {}, 'overall') def test_new_task_resets_root_goal_and_prompt_describes_ranges(self): previous = normalize_task(task_value(period={'year': 2025}), '旧目标', {}) previous['rootGoal'] = '旧根目标' context = bind_task({'_protocol': {'version': 1}}, previous) proposal = task_value(kind='metrics', dimensions=[], stages=[], fields=['rate'], goal='客户月度新目标', newTask=True, trendRequired=True, period={'year': 2026, 'monthStart': 1, 'monthEnd': 9}) semantic = {'aligned': True, 'requiresEvidence': True, 'requiresTrend': True, 'requiresComparison': False, 'requiresSourceVerification': False, 'requiresAllSourceRows': False} with patch('nao_agent_task._model_json', side_effect=[proposal, semantic]) as model: planned = plan_task(base_url='https://offline.invalid', api_key='synthetic', model='m', question='新任务:客户1至9月综合合格率趋势', context=context, cancel_event=threading.Event()) self.assertEqual(planned['rootGoal'], '客户月度新目标') prompt = model.call_args_list[0].kwargs['system'] self.assertIn('monthStart', prompt) self.assertIn('单独month只代表该月', prompt) if __name__ == '__main__': unittest.main()