Verify hybrid indexes and punctuation oracle
Browse filesFiles changed (4)
68 unmodified lines6970717273747568 unmodified linesexcept sqlite3.Error as exc:raise CorpusIntegrityError(f"cannot read newspaper text {doc_id}: {exc}") from excif row is None:raise CorpusUnavailable(f"newspaper text is missing: {doc_id}")text = row[0]if not isinstance(text, str):raise CorpusIntegrityError(f"newspaper text is not a string: {doc_id}")68 unmodified lines6970717273747568 unmodified linesexcept sqlite3.Error as exc:raise CorpusIntegrityError(f"cannot read newspaper text {doc_id}: {exc}") from excif row is None:raise CorpusIntegrityError(f"newspaper text is missing: {doc_id}")text = row[0]if not isinstance(text, str):raise CorpusIntegrityError(f"newspaper text is not a string: {doc_id}")
1234566 unmodified lines1314151617181963 unmodified lines83848586878815 unmodified lines104105106107108109110from __future__ import annotationsimport hashlibimport sqlite3import tempfileimport unittest6 unmodified linesimport build_fulltext_dbfrom tests.corpus_reader import CorpusIntegrityError, CorpusReader, CorpusUnavailablefrom tests.test_integration import create_fts_databasefrom tests.test_search_oracle import matching_body_queries, prepare_body_matrixclass CorpusReaderTests(unittest.TestCase):63 unmodified lines{("手?机", True), ("手*机", True), ("文化 革命", False), ("ABC", True)})self.assertIn(("手机", True), matching_body_queries("手机", prepared))def test_read_files_and_sqlite_with_pinned_integrity(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory)15 unmodified linesreader.read_text({**sqlite_record, "size": len(raw) + 1})with self.assertRaisesRegex(ValueError, "pinned metadata"):reader.read_text({**sqlite_record, "text_sha256": "0" * 64})with self.assertRaises(CorpusUnavailable):reader.read_text({**sqlite_record, "doc_id": "RMRB:missing"})with self.assertRaises(CorpusUnavailable):reader.read_text({**file_record, "storage_rel_path": "missing.txt"})123456786 unmodified lines151617181920212263 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512615 unmodified lines142143144145146147148from __future__ import annotationsimport gzipimport hashlibimport jsonimport sqlite3import tempfileimport unittest6 unmodified linesimport build_fulltext_dbfrom tests.corpus_reader import CorpusIntegrityError, CorpusReader, CorpusUnavailablefrom tests.test_integration import create_fts_databasefrom tests import test_search_oracle as oraclefrom tests.test_search_oracle import matching_body_queries, metadata_match, oracle_execution_exact, prepare_body_matrixclass CorpusReaderTests(unittest.TestCase):63 unmodified lines{("手?机", True), ("手*机", True), ("文化 革命", False), ("ABC", True)})self.assertIn(("手机", True), matching_body_queries("手机", prepared))def test_oracle_uses_http_punctuation_execution_mode(self):cases = [("手。机", True), ("手机", True), ("手*机", True), ("手?机", True), ("手。机", False)]self.assertFalse(oracle_execution_exact("手。机", True))self.assertTrue(oracle_execution_exact("手*机", True))prepared = prepare_body_matrix(cases)record = {"display_name": "手册和机器", "source_name": "资料", "display_rel_path": "资料.txt"}self.assertEqual(set(matching_body_queries("手册和机器", prepared)), {("手。机", True), ("手。机", False), ("手*机", True)})self.assertTrue(metadata_match(record, "手。机", oracle_execution_exact("手。机", True), True))self.assertFalse(metadata_match(record, "手。机", True, True))self.assertEqual(matching_body_queries("任意内容", prepare_body_matrix([("。", True)])), [])with tempfile.TemporaryDirectory() as directory:root = Path(directory)create_fts_database(root / "CCRD.sqlite3", [(1, "手册和机器"), (2, "手机"), (3, "无关")])database = app.FulltextDatabases(root)try:self.assertEqual(database.search_source("CCRD", "手。机", oracle_execution_exact("手。机", True)), {1, 2})finally:database.close()def test_missing_newspaper_row_fails_oracle_instead_of_being_skipped(self):text = "第一篇"with tempfile.TemporaryDirectory() as directory:root = Path(directory)(root / "data").mkdir()with sqlite3.connect(root / "RMRB.sqlite3") as connection:connection.execute("CREATE TABLE texts (doc_id TEXT PRIMARY KEY, body TEXT NOT NULL)")connection.execute("INSERT INTO texts VALUES ('RMRB:1', ?)", (text,))record = {"doc_id": "RMRB:2", "source": "RMRB", "text_storage": "sqlite", "size": 0, "text_sha256": "0" * 64}(root / "data/search_data.json.gz").write_bytes(gzip.compress(json.dumps({"records": [record]}).encode()))with patch("tests.test_search_oracle.BASE_DIR", root), patch("tests.test_search_oracle.SQLITE_DIR", root), \patch.object(oracle.ProductionSearchOracleTests, "request_json", return_value={"ready": True}):with self.assertRaisesRegex(CorpusIntegrityError, "newspaper text is missing"):oracle.ProductionSearchOracleTests.setUpClass()def test_read_files_and_sqlite_with_pinned_integrity(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory)15 unmodified linesreader.read_text({**sqlite_record, "size": len(raw) + 1})with self.assertRaisesRegex(ValueError, "pinned metadata"):reader.read_text({**sqlite_record, "text_sha256": "0" * 64})with self.assertRaisesRegex(CorpusIntegrityError, "newspaper text is missing"):reader.read_text({**sqlite_record, "doc_id": "RMRB:missing"})with self.assertRaises(CorpusUnavailable):reader.read_text({**file_record, "storage_rel_path": "missing.txt"})
65 unmodified lines66676869707165 unmodified linesclass FulltextIntegrationTests(unittest.TestCase):def test_fixture_fts_matches_production_normalization(self):text = "ABC\x00文化革命"with tempfile.TemporaryDirectory() as directory:65 unmodified lines6667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613765 unmodified linesclass FulltextIntegrationTests(unittest.TestCase):def test_newspaper_hybrid_database_rejects_incomplete_and_mismatched_rows(self):cases = ("valid", "wrong_profile", "missing_complete", "missing_texts", "wrong_version","missing_doc_counts", "missing_fts", "mismatched_ids", "empty")for case in cases:with self.subTest(case=case), tempfile.TemporaryDirectory() as directory:root = Path(directory)path = root / "RMRB.sqlite3"create_fts_database(path, [] if case == "empty" else [(1, "手机正文")])with sqlite3.connect(path) as connection:connection.execute("UPDATE documents SET doc_id='RMRB:1' WHERE doc_id='CCRD:1'")connection.execute("INSERT INTO metadata VALUES ('index_profile', ?)",("unsupported" if case == "wrong_profile" else app.NEWSPAPER_INDEX_PROFILE,))if case != "missing_complete":connection.execute("INSERT INTO metadata VALUES ('build_complete', 'true')")if case == "wrong_version":connection.execute("UPDATE metadata SET value='legacy' WHERE key='tokenizer_version'")if case == "missing_doc_counts":connection.execute("DROP TABLE postings")connection.execute("CREATE TABLE postings (token_hash BLOB PRIMARY KEY, docs BLOB NOT NULL)")if case == "missing_fts":connection.execute("DROP TABLE content_fts")if case != "missing_texts":connection.execute("CREATE TABLE texts (doc_id TEXT PRIMARY KEY, body TEXT NOT NULL)")if case != "empty":connection.execute("INSERT INTO texts VALUES (?, ?)",("RMRB:2" if case == "mismatched_ids" else "RMRB:1", "手机正文"))database = app.FulltextDatabases(root)try:if case == "valid":self.assertTrue(database.hybrid_texts_ready["RMRB"])self.assertIs(database.stored_text("RMRB:1", exists_only=True), True)self.assertEqual(database.stored_text("RMRB:1"), "手机正文")self.assertIsNone(database.stored_text("RMRB:2"))self.assertIsNone(database.stored_text("RMRB:bad"))else:self.assertNotIn("RMRB", database.connections)finally:database.close()def test_invalid_newspaper_replacement_does_not_displace_serving_generation(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory)path = root / "RMRB.sqlite3"create_fts_database(path, [(1, "旧版手机")])with sqlite3.connect(path) as connection:connection.execute("UPDATE documents SET doc_id='RMRB:1' WHERE doc_id='CCRD:1'")connection.execute("CREATE TABLE texts (doc_id TEXT PRIMARY KEY, body TEXT NOT NULL)")connection.execute("INSERT INTO texts VALUES ('RMRB:1', '旧版手机')")connection.execute("INSERT INTO metadata VALUES ('index_profile', ?)", (app.NEWSPAPER_INDEX_PROFILE,))connection.execute("INSERT INTO metadata VALUES ('build_complete', 'true')")database = app.FulltextDatabases(root)try:self.assertEqual(database.stored_text("RMRB:1"), "旧版手机")generation = database.generationreplacement = root / "replacement.tmp"with sqlite3.connect(replacement) as connection:connection.execute("CREATE TABLE unrelated (id INTEGER)")os.replace(replacement, path)database.refresh()self.assertEqual(database.generation, generation)self.assertTrue(database.hybrid_texts_ready["RMRB"])self.assertEqual(database.stored_text("RMRB:1"), "旧版手机")self.assertEqual(database.search_source("RMRB", "手机", exact=True), {1})finally:database.close()def test_fixture_fts_matches_production_normalization(self):text = "ABC\x00文化革命"with tempfile.TemporaryDirectory() as directory:
77 unmodified lines7879808182838485868788891 unmodified line91929394959697989910010110210364 unmodified lines16816917017117217317417517636 unmodified lines21321421521621721877 unmodified linesreturn bool(terms) and all(term in text for term in terms)def prepare_body_matrix(matrix):"""Compile immutable query details once, not once per document."""prepared = []for query, exact in matrix:pattern = wildcard_regex(query) if exact and ("*" in query or "?" in query) else Noneprepared.append(((query, exact), normalize(query), pattern, query_tokens(query) if not exact else None))return prepared1 unmodified linetext = normalize(text)tokens = Nonematches = []for key, needle, pattern, wanted in prepared:if key[1]:matched = bool(pattern.search(text)) if pattern else needle in textelse:if tokens is None:tokens = body_tokens(text)matched = all(token in tokens for token in wanted)if matched:matches.append(key)return matches64 unmodified linesdef expected_ids(self, query: str, exact: bool, fulltext: bool = True, search_paths: bool = True, sources=None, folders=None, min_size=None, max_size=None):body = self.body_matches[(query, exact)] if fulltext else set()result = set()for record in self.records:if record["doc_id"] not in body and not metadata_match(record, query, exact, search_paths):continueif sources and record["source"] not in sources:continue36 unmodified linesself.assertEqual(actual, expected)self.assertEqual(self.body_matches[("ABC", True)], self.body_matches[("ABC", True)])def test_sorting_page_sizes_source_route_and_exact_snippets(self):base = {"q": "手机", "exact": True, "fulltext": True, "search_paths": True, "sources": ["CW"]}expected = self.expected_ids("手机", True, sources=["CW"])77 unmodified lines787980818283848586878889909192939495969798991 unmodified line10110210310410510610710810911011111211364 unmodified lines17817918018118218318418518618736 unmodified lines22422522622722822923023123223323423523623723877 unmodified linesreturn bool(terms) and all(term in text for term in terms)def oracle_execution_exact(query: str, requested_exact: bool) -> bool:"""Punctuation changes HTTP search execution without changing the UI toggle."""return requested_exact and not any(not character.isalnum() and not character.isspace() and character not in "*?"for character in query.strip())def prepare_body_matrix(matrix):"""Compile immutable query details once, not once per document."""prepared = []for query, exact in matrix:executed_exact = oracle_execution_exact(query, exact)pattern = wildcard_regex(query) if executed_exact and ("*" in query or "?" in query) else Noneprepared.append(((query, exact), executed_exact, normalize(query), pattern,query_tokens(query) if not executed_exact else None))return prepared1 unmodified linetext = normalize(text)tokens = Nonematches = []for key, executed_exact, needle, pattern, wanted in prepared:if executed_exact:matched = bool(pattern.search(text)) if pattern else needle in textelse:if tokens is None:tokens = body_tokens(text)matched = bool(wanted) and all(token in tokens for token in wanted)if matched:matches.append(key)return matches64 unmodified linesdef expected_ids(self, query: str, exact: bool, fulltext: bool = True, search_paths: bool = True, sources=None, folders=None, min_size=None, max_size=None):body = self.body_matches[(query, exact)] if fulltext else set()executed_exact = oracle_execution_exact(query, exact)result = set()for record in self.records:if record["doc_id"] not in body and not metadata_match(record, query, executed_exact, search_paths):continueif sources and record["source"] not in sources:continue36 unmodified linesself.assertEqual(actual, expected)self.assertEqual(self.body_matches[("ABC", True)], self.body_matches[("ABC", True)])def test_punctuation_exact_toggle_executes_normal_search(self):for fulltext in (False, True):with self.subTest(fulltext=fulltext):body = {"q": "手。机", "exact": True, "fulltext": fulltext, "sort": "name"}actual, total = self.api_ids(body)expected = self.expected_ids("手。机", True, fulltext=fulltext)self.assertEqual(total, len(expected))self.assertEqual(actual, expected)def test_sorting_page_sizes_source_route_and_exact_snippets(self):base = {"q": "手机", "exact": True, "fulltext": True, "search_paths": True, "sources": ["CW"]}expected = self.expected_ids("手机", True, sources=["CW"])
tests/corpus_reader.py+1-1
tests/test_corpus_reader.py+40-2
tests/test_integration.py+66
tests/test_search_oracle.py+26-6