cbe68efe58
Strategy 3 (Fuzzy/Levenshtein) previously returned True if ANY single keyword word matched ANY text word. For multi-word keywords like 'hermes-gateway', this caused false 100% matches when only 'hermes' appeared in text like 'hermes deployment pipeline'. Fix: ALL keyword words must find a fuzzy match in the text. Single-word keywords still work (one word must match). Words shorter than MIN_FUZZY_LEN that reach Strategy 3 cause the keyword to NOT match (they were already checked by Strategy 1/2). Added 5 unit tests: - test_strategy3_multiword_all_words_match - test_strategy3_multiword_only_one_word_matches (the B-1 scenario) - test_strategy3_multiword_no_words_match - test_strategy3_single_word_still_works (regression) - test_strategy3_multiword_fuzzy_typo Applied to both match_keyword() and match_keyword_with_stems(). Ref: Rainer's review .hermes/reviews/rainer/test-anpassung-2026-07-29.md
640 lines
28 KiB
Python
640 lines
28 KiB
Python
"""
|
||
Tests für den Keyword-Matcher mit morphologischer Varianten-Erkennung.
|
||
|
||
Testet:
|
||
- GermanStemmer (Snowball German)
|
||
- Levenshtein-Distanz
|
||
- match_keyword() mit allen Strategien
|
||
- Integration in RoomMap.find_room_by_keywords()
|
||
- Integration in RoomMap.is_100_percent_match()
|
||
- False-Positive-Vermeidung (kurze Keywords, semantisch verschieden)
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import sys
|
||
import tempfile
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||
|
||
from plugin.archivar.keyword_matcher import (
|
||
GermanStemmer,
|
||
levenshtein_distance,
|
||
match_keyword,
|
||
match_keyword_exact,
|
||
match_any_keyword,
|
||
find_matching_keywords,
|
||
normalize_text,
|
||
normalize_keyword,
|
||
stem_word,
|
||
stem_phrase,
|
||
match_keyword_with_stems,
|
||
precompute_keyword_stems,
|
||
)
|
||
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# GermanStemmer Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestGermanStemmer:
|
||
"""Snowball German stemmer tests."""
|
||
|
||
def setup_method(self):
|
||
self.stemmer = GermanStemmer()
|
||
|
||
def test_plural_nouns(self):
|
||
"""Pluralformen werden auf Singular reduziert."""
|
||
assert self.stemmer.stem("homelabs") == "homelab"
|
||
assert self.stemmer.stem("dokumentationen") == "dokumentation"
|
||
assert self.stemmer.stem("netzwerke") == "netzwerk"
|
||
assert self.stemmer.stem("subnetze") == "subnetz"
|
||
assert self.stemmer.stem("firewalls") == "firewall"
|
||
|
||
def test_case_declensions(self):
|
||
"""Deklinationsformen werden auf Grundform reduziert."""
|
||
# Genitiv
|
||
assert self.stemmer.stem("homelabes") == "homelab"
|
||
# Dativ Plural
|
||
assert self.stemmer.stem("homelaben") == "homelab"
|
||
|
||
def test_verb_forms(self):
|
||
"""Verbformen werden gestemmt (vereinfachter Stemmer — ein Pass)."""
|
||
# Der vereinfachte Stemmer macht nur einen Pass pro Step.
|
||
# 'laufenden' → Step1 entfernt 'en' → 'laufend'
|
||
# Das reicht für unseren Use Case (Plural/Deklination).
|
||
assert self.stemmer.stem("laufenden") == "laufend"
|
||
assert self.stemmer.stem("gehenden") == "gehend"
|
||
|
||
def test_short_words_unchanged(self):
|
||
"""Sehr kurze Wörter bleiben unverändert."""
|
||
assert self.stemmer.stem("bat") == "bat"
|
||
assert self.stemmer.stem("rc") == "rc"
|
||
assert self.stemmer.stem("ddp") == "ddp"
|
||
|
||
def test_compound_words(self):
|
||
"""Komposita werden korrekt gestemmt (kein Overstemming)."""
|
||
# 'routerkonfiguration' → sollte nicht zu 'routerkonfigura' werden
|
||
# Der Stemmer entfernt 'tion' nicht (aus Suffix-Liste entfernt).
|
||
assert self.stemmer.stem("routerkonfiguration") == "routerkonfiguration"
|
||
assert self.stemmer.stem("netzwerkdokumentation") == "netzwerkdokumentation"
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# Levenshtein Distance Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestLevenshtein:
|
||
"""Levenshtein edit distance tests."""
|
||
|
||
def test_identical(self):
|
||
assert levenshtein_distance("homelab", "homelab") == 0
|
||
|
||
def test_one_edit(self):
|
||
assert levenshtein_distance("homelab", "homelabs") == 1
|
||
assert levenshtein_distance("raummap", "raum-map") == 1
|
||
assert levenshtein_distance("dokumentation", "dokumentationen") == 2
|
||
|
||
def test_two_edits(self):
|
||
assert levenshtein_distance("homelab", "homelap") == 1
|
||
assert levenshtein_distance("abc", "xyz") == 3
|
||
|
||
def test_empty(self):
|
||
assert levenshtein_distance("", "") == 0
|
||
assert levenshtein_distance("abc", "") == 3
|
||
assert levenshtein_distance("", "abc") == 3
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# Normalization Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestNormalization:
|
||
"""Text normalization tests."""
|
||
|
||
def test_lowercase(self):
|
||
assert normalize_text("Homelab") == "homelab"
|
||
|
||
def test_german_special_chars(self):
|
||
assert normalize_text("Übersicht") == "uebersicht"
|
||
assert normalize_text("Öffnen") == "oeffnen"
|
||
assert normalize_text("Ändern") == "aendern"
|
||
assert normalize_text("Straße") == "strasse"
|
||
|
||
def test_keyword_hyphen_removal(self):
|
||
assert normalize_keyword("raum-map") == "raum map"
|
||
assert normalize_keyword("hardware-übersicht") == "hardware uebersicht"
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# match_keyword() — Core Bug-Report Test Cases
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestMatchKeyword:
|
||
"""Core match_keyword() tests from the bug report."""
|
||
|
||
# ── Morphological variants (Plural, Deklination) ─────────────────
|
||
|
||
def test_plural_homelabs(self):
|
||
"""'homelab' vs 'Homelabs' → MATCH"""
|
||
assert match_keyword("homelab", "Homelabs") is True
|
||
|
||
def test_dativ_homelab(self):
|
||
"""'homelab' vs 'dem Homelab' → MATCH"""
|
||
assert match_keyword("homelab", "dem Homelab") is True
|
||
|
||
def test_genitiv_homelab(self):
|
||
"""'homelab' vs 'Homelabes' → MATCH"""
|
||
assert match_keyword("homelab", "Homelabes") is True
|
||
|
||
def test_dativ_plural_homelab(self):
|
||
"""'homelab' vs 'Homelaben' → MATCH"""
|
||
assert match_keyword("homelab", "Homelaben") is True
|
||
|
||
def test_plural_dokumentation(self):
|
||
"""'dokumentation' vs 'Dokumentationen' → MATCH"""
|
||
assert match_keyword("dokumentation", "Dokumentationen") is True
|
||
|
||
def test_plural_netzwerk(self):
|
||
"""'netzwerk' vs 'Netzwerke' → MATCH"""
|
||
assert match_keyword("netzwerk", "Netzwerke") is True
|
||
|
||
def test_plural_subnetz(self):
|
||
"""'subnetz' vs 'Subnetze' → MATCH"""
|
||
assert match_keyword("subnetz", "Subnetze") is True
|
||
|
||
def test_plural_firewall(self):
|
||
"""'firewall' vs 'Firewalls' → MATCH"""
|
||
assert match_keyword("firewall", "Firewalls") is True
|
||
|
||
# ── Hyphen and punctuation ───────────────────────────────────────
|
||
|
||
def test_hyphen_lan_doku(self):
|
||
"""'lan dokumentation' vs 'LAN-Dokumentation' → MATCH"""
|
||
assert match_keyword("lan dokumentation", "LAN-Dokumentation") is True
|
||
|
||
def test_hyphen_umlaut(self):
|
||
"""'hardware übersicht' vs 'Hardware-Übersicht' → MATCH"""
|
||
assert match_keyword("hardware übersicht", "Hardware-Übersicht") is True
|
||
|
||
def test_punctuation_rocketchat(self):
|
||
"""'rocketchat plugin' vs 'Rocket.Chat Plugins' → MATCH"""
|
||
assert match_keyword("rocketchat plugin", "Rocket.Chat Plugins") is True
|
||
|
||
# ── Case-insensitive ─────────────────────────────────────────────
|
||
|
||
def test_case_insensitive_pfsense(self):
|
||
"""'pfsense' vs 'pfSense' → MATCH"""
|
||
assert match_keyword("pfsense", "pfSense") is True
|
||
|
||
# ── Compounds ────────────────────────────────────────────────────
|
||
|
||
def test_compound_ddp(self):
|
||
"""'ddp' vs 'DDP-WebSocket' → MATCH"""
|
||
assert match_keyword("ddp", "DDP-WebSocket") is True
|
||
|
||
def test_compound_websocket(self):
|
||
"""'websocket' vs 'WebSocket-Verbindung' → MATCH"""
|
||
assert match_keyword("websocket", "WebSocket-Verbindung") is True
|
||
|
||
def test_compound_router(self):
|
||
"""'router' vs 'Routerkonfiguration' → MATCH"""
|
||
assert match_keyword("router", "Routerkonfiguration") is True
|
||
|
||
def test_compound_proxmox(self):
|
||
"""'proxmox' vs 'Proxmox-Server' → MATCH"""
|
||
assert match_keyword("proxmox", "Proxmox-Server") is True
|
||
|
||
# ── Fuzzy matching ────────────────────────────────────────────────
|
||
|
||
def test_fuzzy_raum_map(self):
|
||
"""'raum-map' vs 'Raummap' → MATCH (Fuzzy)"""
|
||
assert match_keyword("raum-map", "Raummap") is True
|
||
|
||
# ── Semantic negatives (should NOT match) ────────────────────────
|
||
|
||
def test_semantic_different_lan_vs_netzwerk(self):
|
||
"""'lan dokumentation' vs 'Netzwerkdokumentation' → KEIN MATCH"""
|
||
assert match_keyword("lan dokumentation", "Netzwerkdokumentation") is False
|
||
|
||
def test_semantic_different_heimnetz_vs_heimarbeit(self):
|
||
"""'heimnetz' vs 'Heimarbeitsplatz' → KEIN MATCH"""
|
||
assert match_keyword("heimnetz", "Heimarbeitsplatz") is False
|
||
|
||
def test_semantic_different_homelab_vs_homeoffice(self):
|
||
"""'homelab' vs 'Homeoffice' → KEIN MATCH"""
|
||
assert match_keyword("homelab", "Homeoffice") is False
|
||
|
||
def test_semantic_different_trading_vs_tradition(self):
|
||
"""'trading' vs 'Tradition' → KEIN MATCH"""
|
||
assert match_keyword("trading", "Tradition") is False
|
||
|
||
# ── Short keyword false-positive prevention ──────────────────────
|
||
|
||
def test_short_keyword_bat_vs_batterie(self):
|
||
"""'bat' vs 'Batterie' → KEIN MATCH (Wortgrenze)"""
|
||
assert match_keyword("bat", "Batterie") is False
|
||
|
||
def test_short_keyword_bat_vs_bat_team(self):
|
||
"""'bat' vs 'BAT-Team' → MATCH (Wortgrenze)"""
|
||
assert match_keyword("bat", "BAT-Team") is True
|
||
|
||
def test_short_keyword_rc_vs_archivar(self):
|
||
"""'rc' vs 'Archivar' → KEIN MATCH (Wortgrenze)"""
|
||
assert match_keyword("rc", "Archivar") is False
|
||
|
||
def test_short_keyword_rc_vs_rc_plugin(self):
|
||
"""'rc' vs 'RC-Plugin' → MATCH (Wortgrenze)"""
|
||
assert match_keyword("rc", "RC-Plugin") is True
|
||
|
||
def test_short_keyword_ddp_vs_ddp_client(self):
|
||
"""'ddp' vs 'DDP-Client' → MATCH"""
|
||
assert match_keyword("ddp", "DDP-Client") is True
|
||
|
||
# ── Strategy 3: Multi-word fuzzy matching (B-1 fix) ───────────────
|
||
|
||
def test_strategy3_multiword_all_words_match(self):
|
||
"""Multi-word keyword: ALL words must fuzzy-match for Strategy 3."""
|
||
# 'hermes gateway' (normalized from 'hermes-gateway') vs
|
||
# 'hermes gateway' → both words match → MATCH
|
||
assert match_keyword("hermes-gateway", "hermes gateway") is True
|
||
|
||
def test_strategy3_multiword_only_one_word_matches(self):
|
||
"""Multi-word keyword: single word match is NOT enough for Strategy 3."""
|
||
# 'hermes gateway' (normalized from 'hermes-gateway') vs
|
||
# 'hermes deployment pipeline' → only 'hermes' matches, 'gateway' doesn't
|
||
# → NO MATCH (B-1 fix)
|
||
assert match_keyword("hermes-gateway", "hermes deployment pipeline") is False
|
||
|
||
def test_strategy3_multiword_no_words_match(self):
|
||
"""Multi-word keyword: no words match → NO MATCH."""
|
||
assert match_keyword("hermes-gateway", "unrelated text here") is False
|
||
|
||
def test_strategy3_single_word_still_works(self):
|
||
"""Single-word keywords still work with Strategy 3 (regression check)."""
|
||
# 'hermes' (single word) vs 'hermes' → MATCH
|
||
assert match_keyword("hermes", "hermes") is True
|
||
# 'hermes' vs 'hermes deployment' → MATCH (exact substring, Strategy 1)
|
||
assert match_keyword("hermes", "hermes deployment") is True
|
||
|
||
def test_strategy3_multiword_fuzzy_typo(self):
|
||
"""Multi-word keyword with minor typo in one word still matches."""
|
||
# 'hermes gateway' vs 'hermes gatewy' (typo in 'gateway')
|
||
# 'hermes' exact match (Strategy 1), 'gatewy' fuzzy-matches 'gateway' (dist=1)
|
||
assert match_keyword("hermes-gateway", "hermes gatewy") is True
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# match_keyword_exact() Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestMatchKeywordExact:
|
||
"""Exact matching (no stemming/fuzzy) for context keywords."""
|
||
|
||
def test_exact_match(self):
|
||
assert match_keyword_exact("docker", "Docker container") is True
|
||
|
||
def test_exact_no_stemming(self):
|
||
"""Exact match should NOT use stemming."""
|
||
# 'container' should NOT match 'Containern' (plural) in exact mode
|
||
assert match_keyword_exact("container", "Containern") is False
|
||
|
||
def test_exact_case_insensitive(self):
|
||
assert match_keyword_exact("DOCKER", "docker") is True
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# match_any_keyword / find_matching_keywords Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestBulkMatching:
|
||
"""Bulk matching helper tests."""
|
||
|
||
def test_match_any(self):
|
||
keywords = ["homelab", "netzwerk", "dokumentation"]
|
||
assert match_any_keyword(keywords, "Homelabs sind wichtig") is True
|
||
assert match_any_keyword(keywords, "Kein Treffer hier") is False
|
||
|
||
def test_find_matching(self):
|
||
keywords = ["homelab", "netzwerk", "dokumentation"]
|
||
matched = find_matching_keywords(keywords, "Homelabs und Netzwerke")
|
||
assert "homelab" in matched
|
||
assert "netzwerk" in matched
|
||
assert "dokumentation" not in matched
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# RoomMap Integration Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
def _make_room_map(rooms_data: list[dict]) -> RoomMap:
|
||
"""Helper: create a RoomMap from room data dicts."""
|
||
rooms = {}
|
||
for r in rooms_data:
|
||
rooms[r["room_id"]] = RoomEntry(
|
||
room_id=r["room_id"],
|
||
name=r.get("name", ""),
|
||
theme=r.get("theme", ""),
|
||
keywords_100=r.get("keywords_100", []),
|
||
keywords_context=r.get("keywords_context", []),
|
||
catch_all=r.get("catch_all", False),
|
||
)
|
||
return RoomMap(
|
||
rooms=rooms,
|
||
excluded_room_ids=set(),
|
||
fact_store_path=Path("/tmp/test"),
|
||
)
|
||
|
||
|
||
class TestRoomMapMorphologicalMatching:
|
||
"""RoomMap integration with morphological keyword matching."""
|
||
|
||
@pytest.fixture
|
||
def room_map(self):
|
||
return _make_room_map([
|
||
{
|
||
"room_id": "r_lan",
|
||
"name": "#LAN-Dokumentation",
|
||
"theme": "LAN docs",
|
||
"keywords_100": ["homelab", "dokumentation", "netzwerk", "lan"],
|
||
"keywords_context": ["docker", "infrastruktur"],
|
||
},
|
||
{
|
||
"room_id": "r_rc",
|
||
"name": "#RC-Plugin",
|
||
"theme": "RC plugin",
|
||
"keywords_100": ["rocketchat", "ddp", "websocket"],
|
||
"keywords_context": ["plugin", "gateway"],
|
||
},
|
||
{
|
||
"room_id": "r_admin",
|
||
"name": "DM Admin",
|
||
"theme": "admin",
|
||
"keywords_100": [],
|
||
"keywords_context": [],
|
||
"catch_all": True,
|
||
},
|
||
])
|
||
|
||
def test_find_room_plural_keyword(self, room_map):
|
||
"""'Homelabs' should match #LAN-Dokumentation via 'homelab' keyword."""
|
||
result = room_map.find_room_by_keywords("Homelabs konfigurieren")
|
||
assert result is not None
|
||
assert result.room_id == "r_lan"
|
||
|
||
def test_find_room_dativ_keyword(self, room_map):
|
||
"""'dem Homelab' should match via 'homelab' keyword."""
|
||
result = room_map.find_room_by_keywords("dem Homelab fehlt RAM")
|
||
assert result is not None
|
||
assert result.room_id == "r_lan"
|
||
|
||
def test_find_room_plural_dokumentation(self, room_map):
|
||
"""'Dokumentationen' should match via 'dokumentation' keyword."""
|
||
result = room_map.find_room_by_keywords("Dokumentationen aktualisieren")
|
||
assert result is not None
|
||
assert result.room_id == "r_lan"
|
||
|
||
def test_find_room_compound_ddp(self, room_map):
|
||
"""'DDP-WebSocket' should match #RC-Plugin via 'ddp' keyword."""
|
||
result = room_map.find_room_by_keywords("DDP-WebSocket Verbindung prüfen")
|
||
assert result is not None
|
||
assert result.room_id == "r_rc"
|
||
|
||
def test_is_100_percent_match_plural(self, room_map):
|
||
"""is_100_percent_match should use morphological matching."""
|
||
lan_room = room_map.get_room_by_id("r_lan")
|
||
assert lan_room is not None
|
||
assert room_map.is_100_percent_match("Homelabs", lan_room) is True
|
||
assert room_map.is_100_percent_match("Dokumentationen", lan_room) is True
|
||
assert room_map.is_100_percent_match("Netzwerke", lan_room) is True
|
||
|
||
def test_is_100_percent_match_false_positive_prevention(self, room_map):
|
||
"""is_100_percent_match should NOT match semantically different words."""
|
||
lan_room = room_map.get_room_by_id("r_lan")
|
||
assert lan_room is not None
|
||
# 'homelab' should NOT match 'Homeoffice'
|
||
assert room_map.is_100_percent_match("Homeoffice", lan_room) is False
|
||
|
||
def test_context_keywords_exact_only(self, room_map):
|
||
"""Context keywords should use exact matching (no stemming)."""
|
||
# 'docker' is a context keyword for #LAN-Dokumentation
|
||
# 'Docker-Container' should match (exact substring)
|
||
result = room_map.find_room_by_keywords("Docker-Container prüfen")
|
||
assert result is not None
|
||
assert result.room_id == "r_lan"
|
||
|
||
def test_100_percent_overrides_context(self, room_map):
|
||
"""100% keyword match should override context keyword match."""
|
||
# 'rocketchat' is 100% for #RC-Plugin, 'docker' is context for #LAN
|
||
# 'rocketchat docker' should go to #RC-Plugin (100% wins)
|
||
result = room_map.find_room_by_keywords("rocketchat docker problem")
|
||
assert result is not None
|
||
assert result.room_id == "r_rc"
|
||
|
||
def test_no_match_semantically_different(self, room_map):
|
||
"""Semantically different words should NOT match."""
|
||
result = room_map.find_room_by_keywords("Homeoffice einrichten")
|
||
assert result is None # No room matches 'Homeoffice'
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# RoomEntry.match_score() Integration Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestRoomEntryMatchScore:
|
||
"""RoomEntry.match_score() with morphological matching."""
|
||
|
||
def test_match_score_plural(self):
|
||
entry = RoomEntry(
|
||
room_id="r1", name="#Test", theme="test",
|
||
keywords_100=["homelab", "dokumentation"],
|
||
keywords_context=["docker"],
|
||
)
|
||
# 'Homelabs' → match 'homelab' (1), 'Dokumentationen' → match 'dokumentation' (1)
|
||
# 'Docker' → match 'docker' (1) = total 3
|
||
score = entry.match_score("Homelabs und Dokumentationen mit Docker")
|
||
assert score == 3
|
||
|
||
def test_match_score_no_false_positive(self):
|
||
entry = RoomEntry(
|
||
room_id="r1", name="#Test", theme="test",
|
||
keywords_100=["bat"],
|
||
keywords_context=[],
|
||
)
|
||
# 'Batterie' should NOT match 'bat' (word boundary)
|
||
score = entry.match_score("Batterie wechseln")
|
||
assert score == 0
|
||
|
||
def test_match_score_context_exact(self):
|
||
entry = RoomEntry(
|
||
room_id="r1", name="#Test", theme="test",
|
||
keywords_100=[],
|
||
keywords_context=["container"],
|
||
)
|
||
# 'Containern' should NOT match 'container' in exact mode
|
||
score = entry.match_score("Containern verwalten")
|
||
assert score == 0
|
||
# 'Container' should match
|
||
score = entry.match_score("Container verwalten")
|
||
assert score == 1
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# N1: Additional False-Positive Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestFalsePositivePrevention:
|
||
"""Additional false-positive tests (N1 from F6 review)."""
|
||
|
||
def test_lan_in_ulan_bator(self):
|
||
"""'lan' should NOT match 'Ulan Bator' (word boundary)."""
|
||
assert match_keyword("lan", "Ulan Bator") is False
|
||
|
||
def test_lan_in_ulan_bator_hyphen(self):
|
||
"""'lan' should NOT match 'Ulan-Bator' (word boundary)."""
|
||
assert match_keyword("lan", "Ulan-Bator") is False
|
||
|
||
def test_bat_in_batterie(self):
|
||
"""'bat' should NOT match 'Batterie' (word boundary)."""
|
||
assert match_keyword("bat", "Batterie") is False
|
||
|
||
def test_bat_in_batterie_compound(self):
|
||
"""'bat' should NOT match 'Batteriewechsel' (word boundary)."""
|
||
assert match_keyword("bat", "Batteriewechsel") is False
|
||
|
||
def test_lan_standalone_matches(self):
|
||
"""'lan' should match 'LAN' as standalone word."""
|
||
assert match_keyword("lan", "LAN") is True
|
||
|
||
def test_lan_in_lan_doku_matches(self):
|
||
"""'lan' should match 'LAN-Dokumentation' (word boundary)."""
|
||
assert match_keyword("lan", "LAN-Dokumentation") is True
|
||
|
||
def test_bat_standalone_matches(self):
|
||
"""'bat' should match 'BAT' as standalone word."""
|
||
assert match_keyword("bat", "BAT") is True
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# R2: Performance Benchmark Tests
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
|
||
class TestPerformanceKeywordMatching:
|
||
"""Performance benchmark tests (R2 from F6 review).
|
||
|
||
Verifies that keyword matching with pre-computed stems completes
|
||
in <50ms for 100 matches.
|
||
"""
|
||
|
||
def test_performance_keyword_matching(self):
|
||
"""Benchmark: 100 keyword matches should complete in <50ms."""
|
||
import time
|
||
|
||
# Simulate a realistic room map with 5 rooms, each with 3-5 keywords
|
||
keywords_list = [
|
||
["homelab", "dokumentation", "netzwerk", "lan"],
|
||
["rocketchat", "ddp", "websocket", "plugin"],
|
||
["proxmox", "virtualisierung", "container", "lxc"],
|
||
["firewall", "pfsense", "opnsense", "vlan"],
|
||
["monitoring", "grafana", "prometheus", "alerting"],
|
||
]
|
||
|
||
# Pre-compute stems for all keywords (R2: once at load time)
|
||
precomputed = []
|
||
for kws in keywords_list:
|
||
precomputed.append([
|
||
(kw, precompute_keyword_stems([kw])[0],
|
||
precompute_keyword_stems([kw])[0].split())
|
||
for kw in kws
|
||
])
|
||
|
||
# Test messages (realistic user inputs)
|
||
messages = [
|
||
"Homelabs konfigurieren mit VLAN",
|
||
"Dokumentationen für das Netzwerk",
|
||
"DDP-WebSocket Verbindung prüfen",
|
||
"Proxmox Container migrieren",
|
||
"Firewalls und pfSense Regeln",
|
||
"Grafana Dashboard für Monitoring",
|
||
"Plugin für Rocket.Chat entwickeln",
|
||
"LXC Container Backup Strategie",
|
||
"OPNsense VLAN Routing Problem",
|
||
"Prometheus Alerting konfigurieren",
|
||
]
|
||
|
||
# Warm-up: run once to fill caches
|
||
for kws in precomputed:
|
||
for kw, stemmed, stemmed_words in kws:
|
||
for msg in messages:
|
||
match_keyword_with_stems(kw, msg, stemmed, stemmed_words)
|
||
|
||
# Benchmark: 100 matches (10 messages × 10 rounds)
|
||
start = time.perf_counter()
|
||
iterations = 10
|
||
for _ in range(iterations):
|
||
for kws in precomputed:
|
||
for kw, stemmed, stemmed_words in kws:
|
||
for msg in messages:
|
||
match_keyword_with_stems(kw, msg, stemmed, stemmed_words)
|
||
|
||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||
total_matches = iterations * sum(len(kws) for kws in precomputed) * len(messages)
|
||
|
||
# R2 requirement: <50ms for 100 matches
|
||
# We're doing ~2000 matches here, so scale accordingly
|
||
per_100_ms = (elapsed_ms / total_matches) * 100
|
||
|
||
assert elapsed_ms < 200, (
|
||
f"Performance too slow: {elapsed_ms:.1f}ms for {total_matches} matches "
|
||
f"(~{per_100_ms:.1f}ms per 100 matches, limit is <50ms per 100)"
|
||
)
|
||
|
||
def test_precompute_keyword_stems(self):
|
||
"""Pre-computed stems should match the same as on-the-fly stemming."""
|
||
keywords = ["homelab", "dokumentation", "netzwerk", "lan dokumentation"]
|
||
precomputed = precompute_keyword_stems(keywords)
|
||
|
||
for kw, pre in zip(keywords, precomputed):
|
||
on_the_fly = stem_phrase(normalize_keyword(kw))
|
||
assert pre == on_the_fly, (
|
||
f"Pre-computed stem mismatch for '{kw}': "
|
||
f"pre={pre!r}, on_the_fly={on_the_fly!r}"
|
||
)
|
||
|
||
def test_match_keyword_with_stems_equivalent(self):
|
||
"""match_keyword_with_stems should produce same results as match_keyword."""
|
||
test_cases = [
|
||
("homelab", "Homelabs konfigurieren", True),
|
||
("dokumentation", "Dokumentationen aktualisieren", True),
|
||
("netzwerk", "Netzwerke einrichten", True),
|
||
("homelab", "Homeoffice einrichten", False),
|
||
("bat", "Batterie wechseln", False),
|
||
("lan", "Ulan Bator", False),
|
||
("ddp", "DDP-WebSocket", True),
|
||
("raum-map", "Raummap", True),
|
||
]
|
||
|
||
for kw, text, expected in test_cases:
|
||
stemmed = precompute_keyword_stems([kw])[0]
|
||
stemmed_words = stemmed.split()
|
||
result = match_keyword_with_stems(kw, text, stemmed, stemmed_words)
|
||
assert result is expected, (
|
||
f"match_keyword_with_stems({kw!r}, {text!r}) = {result}, "
|
||
f"expected {expected}"
|
||
)
|