""" Tests für das selbstlernende Keyword-Gewicht-System. """ import json import os import tempfile import unittest from datetime import datetime, timedelta from pathlib import Path import sys # Add the parent directory to the path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from archivar_state import ArchivarState, KeywordWeightEntry, ManualOverride class TestArchivarStateKeywordWeights(unittest.TestCase): """Tests für das selbstlernende Keyword-Gewicht-System.""" def setUp(self): """Set up test fixtures.""" # Create a temporary file for the state self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json') self.temp_file.close() self.state_file_path = self.temp_file.name self.state = ArchivarState(self.state_file_path) def tearDown(self): """Clean up test fixtures.""" # Remove the temporary file if os.path.exists(self.state_file_path): os.unlink(self.state_file_path) def test_keyword_weight_entry_serialization(self): """Test serialization of KeywordWeightEntry.""" # Create a KeywordWeightEntry now = datetime.now().isoformat() entry = KeywordWeightEntry( weight=0.75, last_updated=now, confirmation_count=3, rejection_count=1, last_confirmation=now ) # Create an ArchivarState and add the entry self.state._keyword_weights = { "test_keyword": { "room1": entry } } # Save and reload self.assertTrue(self.state.save()) new_state = ArchivarState(self.state_file_path) self.assertTrue(new_state.load()) # Check that the entry was loaded correctly self.assertIn("test_keyword", new_state._keyword_weights) self.assertIn("room1", new_state._keyword_weights["test_keyword"]) loaded_entry = new_state._keyword_weights["test_keyword"]["room1"] self.assertEqual(loaded_entry.weight, 0.75) self.assertEqual(loaded_entry.confirmation_count, 3) self.assertEqual(loaded_entry.rejection_count, 1) self.assertEqual(loaded_entry.last_updated, now) self.assertEqual(loaded_entry.last_confirmation, now) def test_manual_override_serialization(self): """Test serialization of ManualOverride.""" # Create a ManualOverride now = datetime.now().isoformat() override = ManualOverride( override_weight=0.9, override_reason="Manual adjustment by admin", override_date=now, override_by="admin_user" ) # Create an ArchivarState and add the override self.state._manual_overrides = { "test_keyword": { "room1": override } } # Save and reload self.assertTrue(self.state.save()) new_state = ArchivarState(self.state_file_path) self.assertTrue(new_state.load()) # Check that the override was loaded correctly self.assertIn("test_keyword", new_state._manual_overrides) self.assertIn("room1", new_state._manual_overrides["test_keyword"]) loaded_override = new_state._manual_overrides["test_keyword"]["room1"] self.assertEqual(loaded_override.override_weight, 0.9) self.assertEqual(loaded_override.override_reason, "Manual adjustment by admin") self.assertEqual(loaded_override.override_date, now) self.assertEqual(loaded_override.override_by, "admin_user") def test_update_keyword_weight_confirm(self): """Test updating keyword weight with confirm feedback.""" # Initialize with a keyword weight self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.5, last_updated=datetime.now().isoformat(), confirmation_count=1, rejection_count=0, last_confirmation=None ), "room2": KeywordWeightEntry( weight=0.3, last_updated=datetime.now().isoformat(), confirmation_count=0, rejection_count=0, last_confirmation=None ) } } # Apply confirm feedback result = self.state.update_keyword_weight("plugin", "room1", "confirm") self.assertTrue(result) # Check that the weight was updated correctly entry = self.state._keyword_weights["plugin"]["room1"] # With learning rate 0.2: new_weight = 0.5 + (1 - 0.5) * 0.2 = 0.6 self.assertAlmostEqual(entry.weight, 0.6, places=2) self.assertEqual(entry.confirmation_count, 2) # Check that other room weights were reduced other_entry = self.state._keyword_weights["plugin"]["room2"] # With learning rate 0.2: reduced_weight = 0.3 - (0.3 * 0.2 / 1) = 0.24 self.assertAlmostEqual(other_entry.weight, 0.24, places=2) def test_update_keyword_weight_stay(self): """Test updating keyword weight with stay feedback.""" # Initialize with a keyword weight self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.5, last_updated=datetime.now().isoformat(), confirmation_count=1, rejection_count=0, last_confirmation=None ), "room2": KeywordWeightEntry( weight=0.3, last_updated=datetime.now().isoformat(), confirmation_count=0, rejection_count=0, last_confirmation=None ) } } # Apply stay feedback result = self.state.update_keyword_weight("plugin", "room1", "stay") self.assertTrue(result) # Check that the weight was updated correctly entry = self.state._keyword_weights["plugin"]["room1"] # With learning rate 0.2: new_weight = 0.5 - 0.5 * 0.2 * 0.5 = 0.45 self.assertAlmostEqual(entry.weight, 0.45, places=2) self.assertEqual(entry.rejection_count, 1) # Check that other room weights were increased other_entry = self.state._keyword_weights["plugin"]["room2"] # With learning rate 0.2: increased_weight = 0.3 + ((1 - 0.3) * 0.2 * 0.5 / 1) = 0.37 self.assertAlmostEqual(other_entry.weight, 0.37, places=2) def test_update_keyword_weight_never(self): """Test updating keyword weight with never feedback.""" # Initialize with a keyword weight self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.5, last_updated=datetime.now().isoformat(), confirmation_count=1, rejection_count=0, last_confirmation=None ) } } # Apply never feedback result = self.state.update_keyword_weight("plugin", "room1", "never") self.assertTrue(result) # Check that the weight was set to 0.0 entry = self.state._keyword_weights["plugin"]["room1"] self.assertEqual(entry.weight, 0.0) self.assertEqual(entry.rejection_count, 2) # Counts as 2 negative confirmations # Check that the keyword was added to sticky_keywords self.assertIn("plugin", self.state._sticky_keywords) self.assertIn("room1", self.state._sticky_keywords["plugin"]) def test_calculate_room_score_with_override(self): """Test calculating room score with manual override.""" # Set up a manual override now = datetime.now().isoformat() self.state._manual_overrides = { "plugin": { "room1": ManualOverride( override_weight=0.9, override_reason="Manual adjustment", override_date=now, override_by="admin" ) } } # Calculate score - should use override score = self.state.calculate_room_score("plugin", "room1") self.assertEqual(score, 0.9) def test_calculate_room_score_with_sticky(self): """Test calculating room score with sticky keyword.""" # Set up a sticky keyword self.state._sticky_keywords = { "plugin": ["room1"] } # Calculate score - should be 0.0 score = self.state.calculate_room_score("plugin", "room1") self.assertEqual(score, 0.0) def test_calculate_room_score_with_learned_weight(self): """Test calculating room score with learned weight.""" # Set up a learned weight now = datetime.now().isoformat() self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.7, last_updated=now, confirmation_count=2, rejection_count=0, last_confirmation=now ) } } # Calculate score - should use learned weight score = self.state.calculate_room_score("plugin", "room1") self.assertEqual(score, 0.7) def test_check_promotion_eligibility(self): """Test checking promotion eligibility.""" # Set up a promotable keyword now = datetime.now().isoformat() self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.9, last_updated=now, confirmation_count=3, rejection_count=0, last_confirmation=now ) } } # Check promotion eligibility result = self.state.check_promotion_eligibility("plugin", "room1") self.assertTrue(result) # Check that it was added to promotion candidates self.assertIn("plugin", self.state._promotion_candidates) self.assertIn("room1", self.state._promotion_candidates["plugin"]) def test_apply_decay(self): """Test applying time-based decay.""" # Set up a keyword weight with old last_updated date (45 days ago) old_date = (datetime.now() - timedelta(days=45)).isoformat() self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.8, last_updated=old_date, confirmation_count=2, rejection_count=0, last_confirmation=old_date ) } } # Apply decay result = self.state.apply_decay() self.assertTrue(result) # Check that the weight was reduced (45 days is between 30 and 90 days, # so it should be reduced by 10%) entry = self.state._keyword_weights["plugin"]["room1"] self.assertAlmostEqual(entry.weight, 0.8 * 0.9, places=2) # 0.72 # Test 90-day decay very_old_date = (datetime.now() - timedelta(days=95)).isoformat() self.state._keyword_weights = { "plugin": { "room1": KeywordWeightEntry( weight=0.8, last_updated=very_old_date, confirmation_count=2, rejection_count=0, last_confirmation=very_old_date ) } } # Apply decay result = self.state.apply_decay() self.assertTrue(result) # Check that the weight was reduced by 30% (90 days = 30% reduction) entry = self.state._keyword_weights["plugin"]["room1"] self.assertAlmostEqual(entry.weight, 0.8 * 0.7, places=2) # 0.56 if __name__ == '__main__': unittest.main()