""" Tests for shared_tools utility functions. Tests cover: - Date/time utilities - Validation helpers - Error formatting - Data transformation helpers """ import unittest from datetime import datetime, timedelta, timezone from backend.mcp.agent.shared_tools import ( # Date/time get_current_timestamp, get_current_date_iso, get_date_n_days_ago, get_timestamp_n_days_ago, parse_iso_datetime, calculate_days_between, is_new_day_since, generate_session_id, # Validation validate_text_length, validate_required_fields, validate_date_range, sanitize_dict, extract_field, # Error formatting format_error_response, log_agent_error, create_error_patch, # Data transformation pick_random_message, merge_dicts, flatten_nested_dict, # Agent-specific praise_no_contact_if_new_day, ) class TestDateTimeUtilities(unittest.TestCase): def test_get_current_timestamp(self): """Test current timestamp generation""" ts = get_current_timestamp() self.assertIsInstance(ts, str) self.assertIn('T', ts) # ISO format has T separator def test_get_current_date_iso(self): """Test current date generation""" date = get_current_date_iso() self.assertIsInstance(date, str) self.assertEqual(len(date), 10) # YYYY-MM-DD def test_get_date_n_days_ago(self): """Test past date calculation""" date = get_date_n_days_ago(7) self.assertIsInstance(date, str) # Should be 7 days ago expected = (datetime.now(timezone.utc) - timedelta(days=7)).date().isoformat() self.assertEqual(date, expected) def test_parse_iso_datetime(self): """Test ISO datetime parsing""" iso_str = "2025-11-09T10:30:00" dt = parse_iso_datetime(iso_str) self.assertIsInstance(dt, datetime) self.assertEqual(dt.year, 2025) def test_parse_iso_datetime_invalid(self): """Test ISO datetime parsing with invalid input""" result = parse_iso_datetime("invalid") self.assertIsNone(result) def test_calculate_days_between(self): """Test day calculation between dates""" start = "2025-11-01T00:00:00" end = "2025-11-09T00:00:00" days = calculate_days_between(start, end) self.assertEqual(days, 8) def test_is_new_day_since(self): """Test new day check""" yesterday = get_date_n_days_ago(1) self.assertTrue(is_new_day_since(yesterday)) today = get_current_date_iso() self.assertFalse(is_new_day_since(today)) def test_generate_session_id(self): """Test session ID generation""" sid = generate_session_id() self.assertTrue(sid.startswith('session_')) self.assertTrue(sid[8:].isdigit()) class TestValidationHelpers(unittest.TestCase): def test_validate_text_length_valid(self): """Test text length validation with valid input""" result = validate_text_length("Hello world", 1, 100) self.assertIsNone(result) def test_validate_text_length_too_short(self): """Test text length validation with too short input""" result = validate_text_length("", 1, 100) self.assertIsNotNone(result) self.assertIn("cannot be empty", result) def test_validate_text_length_too_long(self): """Test text length validation with too long input""" result = validate_text_length("x" * 101, 1, 100) self.assertIsNotNone(result) self.assertIn("too long", result) def test_validate_required_fields_valid(self): """Test required fields validation with valid input""" data = {"name": "Test", "age": 30} result = validate_required_fields(data, ["name", "age"]) self.assertIsNone(result) def test_validate_required_fields_missing(self): """Test required fields validation with missing fields""" data = {"name": "Test"} result = validate_required_fields(data, ["name", "age"]) self.assertIsNotNone(result) self.assertIn("Missing", result) def test_validate_date_range_valid(self): """Test date range validation with valid dates""" today = get_current_date_iso() yesterday = get_date_n_days_ago(1) tomorrow = (datetime.now(timezone.utc) + timedelta(days=1)).date().isoformat() result = validate_date_range(today, yesterday, tomorrow) self.assertTrue(result) def test_sanitize_dict(self): """Test dict sanitization""" data = {"a": 1, "b": 2, "c": 3} result = sanitize_dict(data, ["a", "b"]) self.assertEqual(result, {"a": 1, "b": 2}) def test_extract_field_present(self): """Test field extraction with present field""" data = {"name": "Test"} result = extract_field(data, "name", "default") self.assertEqual(result, "Test") def test_extract_field_missing(self): """Test field extraction with missing field""" data = {"name": "Test"} result = extract_field(data, "age", 0) self.assertEqual(result, 0) def test_extract_field_type_check(self): """Test field extraction with type validation""" data = {"age": "30"} # Wrong type result = extract_field(data, "age", 0, field_type=int) self.assertEqual(result, 0) # Should return default class TestErrorFormatting(unittest.TestCase): def test_format_error_response(self): """Test error response formatting""" error = ValueError("Test error") result = format_error_response(error, "test context") self.assertFalse(result['success']) self.assertEqual(result['error'], 'ValueError') self.assertIn('test context', result['message']) def test_create_error_patch(self): """Test error patch creation""" result = create_error_patch("Test error", "test_agent") self.assertFalse(result['success']) self.assertIn('patch', result) self.assertEqual(result['message'], "Test error") class TestDataTransformation(unittest.TestCase): def test_pick_random_message(self): """Test random message picking""" messages = ["Hello", "World", "Test"] result = pick_random_message(messages) self.assertIn(result, messages) def test_pick_random_message_empty(self): """Test random message picking with empty list""" result = pick_random_message([]) self.assertEqual(result, "") def test_merge_dicts(self): """Test dict merging""" d1 = {"a": 1, "b": 2} d2 = {"b": 3, "c": 4} result = merge_dicts(d1, d2) self.assertEqual(result, {"a": 1, "b": 3, "c": 4}) def test_flatten_nested_dict(self): """Test nested dict flattening""" data = {"a": 1, "b": {"c": 2, "d": {"e": 3}}} result = flatten_nested_dict(data) self.assertEqual(result, {"a": 1, "b.c": 2, "b.d.e": 3}) class TestPraiseNoContact(unittest.TestCase): def test_praise_no_contact_new_day(self): """Test praise generation for new day""" result = praise_no_contact_if_new_day("test_agent") self.assertTrue(result['success']) # May or may not be praised depending on implementation self.assertIn('praised', result) def test_praise_no_contact_structure(self): """Test praise response structure""" result = praise_no_contact_if_new_day("test_agent") required_fields = ['success', 'praised', 'message'] for field in required_fields: self.assertIn(field, result) if __name__ == '__main__': unittest.main()