Reject corrupted corpus databases in oracle tests
Browse filesFiles changed (2)
18 unmodified lines19202122232419 unmodified lines444546474849509 unmodified lines6061626364656667686970717218 unmodified lines"""Required originals or a newspaper database are absent."""class CorpusReader:def __init__(self, base_dir: Path, sqlite_dir: Path | None = None):self.base_dir = base_dir19 unmodified linespath = self.sqlite_dir / f"{source}.sqlite3"if not path.is_file():raise CorpusUnavailable(f"newspaper database is missing: {path}")connection = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)self._stack.callback(connection.close)self._connections[source] = connectionreturn self._connections[source]9 unmodified linestry:row = self.database(record["source"]).execute("SELECT body FROM texts WHERE doc_id=?", (doc_id,)).fetchone()except sqlite3.Error as exc:raise CorpusUnavailable(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 ValueError(f"newspaper text is not a string: {doc_id}")encoded = text.encode("utf-8")if len(encoded) != record["size"] or hashlib.sha256(encoded).hexdigest() != record.get("text_sha256"):raise ValueError(f"newspaper text differs from pinned metadata: {doc_id}")return text18 unmodified lines1920212223242526272819 unmodified lines484950515253545556579 unmodified lines6768697071727374757677787918 unmodified lines"""Required originals or a newspaper database are absent."""class CorpusIntegrityError(ValueError):"""A present corpus artifact is malformed, unreadable, or inconsistent."""class CorpusReader:def __init__(self, base_dir: Path, sqlite_dir: Path | None = None):self.base_dir = base_dir19 unmodified linespath = self.sqlite_dir / f"{source}.sqlite3"if not path.is_file():raise CorpusUnavailable(f"newspaper database is missing: {path}")try:connection = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)except sqlite3.Error as exc:raise CorpusIntegrityError(f"cannot open newspaper database {path}: {exc}") from excself._stack.callback(connection.close)self._connections[source] = connectionreturn self._connections[source]9 unmodified linestry:row = self.database(record["source"]).execute("SELECT body FROM texts WHERE doc_id=?", (doc_id,)).fetchone()except 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}")encoded = text.encode("utf-8")if len(encoded) != record["size"] or hashlib.sha256(encoded).hexdigest() != record.get("text_sha256"):raise CorpusIntegrityError(f"newspaper text differs from pinned metadata: {doc_id}")return text
5 unmodified lines67891011121314151640 unmodified lines575859606162635 unmodified linesimport unittestfrom pathlib import Pathfrom tests.corpus_reader import CorpusReader, CorpusUnavailablefrom tests.test_search_oracle import matching_body_queries, prepare_body_matrixclass CorpusReaderTests(unittest.TestCase):def test_independent_body_matching_supports_exact_normalized_and_wildcards(self):matrix = [("手机", True), ("手?机", True), ("手*机", True), ("文化 革命", False),("ABC", True), ("不存在", True)]40 unmodified linesroot = Path(directory)with sqlite3.connect(root / "PLA.sqlite3") as connection:connection.execute("CREATE TABLE unrelated (id INTEGER)")with CorpusReader(root, root) as reader, self.assertRaisesRegex(CorpusUnavailable, "cannot read newspaper text"):reader.read_text({"doc_id": "PLA:1", "source": "PLA", "text_storage": "sqlite", "size": 0})5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505140 unmodified lines929394959697985 unmodified linesimport unittestfrom pathlib import Pathimport appimport 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):def test_search_postings_match_independent_complete_fixture_oracle(self):rows = [(1, "手机资料"), (2, "手。机 文化 革命"), (3, "ABC 文化革命"), (4, "无关正文")]matrix = [("手机", True), ("手?机", True), ("手*机", True),("文化 革命", False), ("ABC", True), ("不存在", True)]prepared = prepare_body_matrix(matrix)with tempfile.TemporaryDirectory() as directory:root = Path(directory)(root / "CCRD").mkdir()records = []for number, text in rows:filename = f"{number}.txt"(root / "CCRD" / filename).write_text(text, encoding="utf-8")records.append({"doc_id": f"CCRD:{number}", "source": "CCRD", "storage_root": "CCRD", "storage_rel_path": filename})create_fts_database(root / "CCRD.sqlite3", rows)# Match the production builder's stored normalized FTS text. The# oracle below still reads and normalizes independent originals.with sqlite3.connect(root / "CCRD.sqlite3") as connection:for number, text in rows:connection.execute("UPDATE content_fts SET content=? WHERE rowid=?", (build_fulltext_db.fts_content(text), number))expected = {query: set() for query in matrix}with CorpusReader(root, root) as reader:for record in records:for query in matching_body_queries(reader.read_text(record), prepared):expected[query].add(int(record["doc_id"].split(":")[1]))database = app.FulltextDatabases(root)try:for query, exact in matrix:with self.subTest(query=query, exact=exact):self.assertEqual(database.search_source("CCRD", query, exact), expected[(query, exact)])finally:database.close()def test_independent_body_matching_supports_exact_normalized_and_wildcards(self):matrix = [("手机", True), ("手?机", True), ("手*机", True), ("文化 革命", False),("ABC", True), ("不存在", True)]40 unmodified linesroot = Path(directory)with sqlite3.connect(root / "PLA.sqlite3") as connection:connection.execute("CREATE TABLE unrelated (id INTEGER)")with CorpusReader(root, root) as reader, self.assertRaisesRegex(CorpusIntegrityError, "cannot read newspaper text"):reader.read_text({"doc_id": "PLA:1", "source": "PLA", "text_storage": "sqlite", "size": 0})
tests/corpus_reader.py+11-4
tests/test_corpus_reader.py+37-2