Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
test(normalize): make optional tests deterministic (#881)
aoright18f1d55d77e4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1107d74b..1c46543b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Three `tests/normalize/` tests failed for reasons unrelated to the normalize implementations: a missing optional-dependency skip guard, an incomplete chardet allowlist, and a UTC/local timezone mismatch** (#881, closes #860) by @aoright+ - `test_detect_language`/`test_detect_with_confidence` in `tests/normalize/test_language_detector.py` asserted on real `langdetect` output with no skip guard, even though `langdetect` is an optional dependency absent from `pyproject.toml` that `LanguageDetector` already degrades gracefully without (`LANGDETECT_AVAILABLE = False`, falls back to `default_language`) — any environment without it failed both tests unconditionally, including a fresh CI run without optional extras installed. Both are now gated with `@unittest.skipUnless(LANGDETECT_AVAILABLE, ...)`+ - `test_detect_encoding` in `tests/normalize/test_encoding_handler.py` asserted `chardet.detect()`'s result against a 3-name allowlist (`iso-8859-1`/`windows-1252`/`latin-1`); on a short Latin-1 sample, chardet is free to return other compatible single-byte codepages (e.g. `windows-1253`), which fails the allowlist and then cascades into `test_convert_to_utf8` decoding the bytes as Greek instead of the original text. The test now uses a longer, unambiguous Latin-1 corpus and asserts that the detected encoding round-trip-decodes the original text instead of matching a fixed name list; `test_convert_to_utf8` now passes `source_encoding="latin-1"` explicitly rather than relying on chardet's heuristic auto-detection+ - `test_normalize_date_relative` in `tests/normalize/test_date_normalizer.py` compared `RelativeDateProcessor`'s local-clock-based `"today"` (`datetime.now()`, naive, UTC-normalized after the fact by `convert_to_utc()`) against a separately-computed UTC reference date — failing intermittently in any timezone east of UTC whenever the local and UTC dates diverge for part of the day. The test now patches `datetime.now()` to a fixed reference time, making the assertion independent of host timezone+ - `pytest tests/normalize`: 77 passed, 2 skipped (`langdetect` not installed); `black`/`isort`/`flake8 --max-line-length=88` clean on all three changed files. Test-only change; no production code touched+- **MCP server reported a stale `0.4.0` version instead of the installed package version** (#870, closes #863) by @oiahoon- `semantica/mcp_server/__init__.py` hardcoded `"version": "0.4.0"` in both the MCP `initialize` response (`SERVER_INFO`) and the `semantica://schema/info` resource, regardless of the actual installed `semantica` version — every MCP client (Claude Desktop, Windsurf, Cline, Continue, VS Code Copilot, etc.) showed the wrong server version. Both surfaces now derive from `semantica.__version__`, the package's authoritative version source, so they can no longer drift from `pyproject.toml`- New regression coverage in `tests/test_mcp_server_version.py`, including `!= "0.4.0"` canaries and a cross-surface consistency checkdiff --git a/tests/normalize/test_date_normalizer.py b/tests/normalize/test_date_normalizer.pyindex 412d8a5b..9c1bb889 100644--- a/tests/normalize/test_date_normalizer.py+++ b/tests/normalize/test_date_normalizer.py@@ -1,12 +1,14 @@import unittest-from datetime import datetime, date, timedelta, timezone+from datetime import datetime, timedelta, timezone+from unittest.mock import patch+from semantica.normalize.date_normalizer import (DateNormalizer,- TimeZoneNormalizer,RelativeDateProcessor,- TemporalExpressionParser+ TimeZoneNormalizer,)+class TestDateNormalizer(unittest.TestCase):def setUp(self):self.normalizer = DateNormalizer()@@ -14,39 +16,42 @@ class TestDateNormalizer(unittest.TestCase):def test_normalize_date_iso(self):# Test ISO8601 parsingself.assertEqual(- self.normalizer.normalize_date("2023-01-01", format="date"),- "2023-01-01"+ self.normalizer.normalize_date("2023-01-01", format="date"), "2023-01-01")self.assertEqual(self.normalizer.normalize_date("2023-01-01T12:00:00", format="ISO8601"),- "2023-01-01T12:00:00+00:00"+ "2023-01-01T12:00:00+00:00",)def test_normalize_date_relative(self):- # Test relative date parsing (e.g., "today", "yesterday")- # Note: These depend on current date, so we might need to mock datetime if strictly testing logic,- # but for now we'll assume the relative processor uses current time.- # We can check if it returns a valid ISO date string.- today = datetime.now(timezone.utc).date().isoformat()- self.assertEqual(- self.normalizer.normalize_date("today", format="date"),- today- )+ class FixedDateTime(datetime):+ @classmethod+ def now(cls, tz=None):+ fixed = cls(2024, 1, 2, 0, 30)+ return fixed if tz is None else fixed.replace(tzinfo=tz)++ with patch("semantica.normalize.date_normalizer.datetime", FixedDateTime):+ self.assertEqual(+ self.normalizer.normalize_date("today", format="date"),+ "2024-01-02",+ )def test_normalize_timezone(self):# Test timezone conversion# "2023-01-01T12:00:00+01:00" -> UTC should be "2023-01-01T11:00:00+00:00"normalized = self.normalizer.normalize_date(- "2023-01-01T12:00:00+01:00",- timezone="UTC"+ "2023-01-01T12:00:00+01:00", timezone="UTC")self.assertEqual(normalized, "2023-01-01T11:00:00+00:00")def test_parse_temporal_expression(self):# Test range parsing- result = self.normalizer.parse_temporal_expression("from 2023-01-01 to 2023-01-31")+ result = self.normalizer.parse_temporal_expression(+ "from 2023-01-01 to 2023-01-31"+ )self.assertIsNotNone(result.get("range"))+class TestTimeZoneNormalizer(unittest.TestCase):def setUp(self):self.tz_normalizer = TimeZoneNormalizer()@@ -56,7 +61,10 @@ class TestTimeZoneNormalizer(unittest.TestCase):# Assuming default is UTC if not specified or naivenormalized = self.tz_normalizer.normalize_timezone(dt, "UTC")# Check offset instead of object identity- self.assertEqual(normalized.tzinfo.utcoffset(normalized), timezone.utc.utcoffset(None))+ self.assertEqual(+ normalized.tzinfo.utcoffset(normalized), timezone.utc.utcoffset(None)+ )+class TestRelativeDateProcessor(unittest.TestCase):def setUp(self):@@ -71,5 +79,6 @@ class TestRelativeDateProcessor(unittest.TestCase):diff = datetime.now() - dtself.assertTrue(timedelta(days=2, hours=23) < diff < timedelta(days=3, hours=1))+if __name__ == "__main__":unittest.main()diff --git a/tests/normalize/test_encoding_handler.py b/tests/normalize/test_encoding_handler.pyindex 4d99198a..ac123bdb 100644--- a/tests/normalize/test_encoding_handler.py+++ b/tests/normalize/test_encoding_handler.py@@ -1,35 +1,41 @@import unittest-import os+from semantica.normalize.encoding_handler import EncodingHandler+class TestEncodingHandler(unittest.TestCase):def setUp(self):self.handler = EncodingHandler()def test_detect_encoding(self):# UTF-8- text = "Héllò Wörld"+ text = (+ "C'était déjà l'été à Montréal; François dégustait un café près "+ "de l'hôtel. "+ ) * 4utf8_bytes = text.encode("utf-8")- encoding, conf = self.handler.detect(utf8_bytes)+ encoding, _ = self.handler.detect(utf8_bytes)self.assertEqual(encoding.lower(), "utf-8")-+# Latin-1latin1_bytes = text.encode("latin-1")- encoding, conf = self.handler.detect(latin1_bytes)- # chardet might return ISO-8859-1 or Windows-1252 which are compatible- self.assertIn(encoding.lower(), ["iso-8859-1", "windows-1252", "latin-1"])+ encoding, _ = self.handler.detect(latin1_bytes)+ # Different chardet versions may choose different compatible codecs.+ self.assertEqual(latin1_bytes.decode(encoding), text)def test_convert_to_utf8(self):text = "Héllò Wörld"latin1_bytes = text.encode("latin-1")- converted = self.handler.convert_to_utf8(latin1_bytes)+ converted = self.handler.convert_to_utf8(+ latin1_bytes, source_encoding="latin-1"+ )self.assertEqual(converted, text)def test_remove_bom(self):# UTF-8 BOMbom_bytes = b"\xef\xbb\xbfHello"self.assertEqual(self.handler.remove_bom(bom_bytes), b"Hello")-+# String BOMbom_str = "\ufeffHello"self.assertEqual(self.handler.remove_bom(bom_str), "Hello")@@ -39,5 +45,6 @@ class TestEncodingHandler(unittest.TestCase):# Invalid sequence for asciiself.assertFalse(self.handler.validate_encoding("Héllò", "ascii"))+if __name__ == "__main__":unittest.main()diff --git a/tests/normalize/test_language_detector.py b/tests/normalize/test_language_detector.pyindex ffee337c..2f10fc29 100644--- a/tests/normalize/test_language_detector.py+++ b/tests/normalize/test_language_detector.py@@ -1,24 +1,39 @@import unittest-from semantica.normalize.language_detector import LanguageDetector++from semantica.normalize.language_detector import (+ LANGDETECT_AVAILABLE,+ LanguageDetector,+)+class TestLanguageDetector(unittest.TestCase):def setUp(self):self.detector = LanguageDetector()+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")def test_detect_language(self):# English- self.assertEqual(self.detector.detect("This is a simple English sentence."), "en")+ self.assertEqual(+ self.detector.detect("This is a simple English sentence."), "en"+ )# French- self.assertEqual(self.detector.detect("Ceci est une phrase française simple."), "fr")+ self.assertEqual(+ self.detector.detect("Ceci est une phrase française simple."), "fr"+ )# German- self.assertEqual(self.detector.detect("Dies ist ein einfacher deutscher Satz."), "de")+ self.assertEqual(+ self.detector.detect("Dies ist ein einfacher deutscher Satz."), "de"+ )def test_detect_short_text(self):# Should return default for very short textself.assertEqual(self.detector.detect("Hi"), "en")+ @unittest.skipUnless(LANGDETECT_AVAILABLE, "langdetect is not installed")def test_detect_with_confidence(self):- lang, conf = self.detector.detect_with_confidence("This is definitely an English sentence.")+ lang, conf = self.detector.detect_with_confidence(+ "This is definitely an English sentence."+ )self.assertEqual(lang, "en")self.assertGreater(conf, 0.5)@@ -27,5 +42,6 @@ class TestLanguageDetector(unittest.TestCase):self.assertEqual(self.detector.get_language_name("fr"), "French")self.assertEqual(self.detector.get_language_name("xx"), "XX")+if __name__ == "__main__":unittest.main()