vomebook commited on
Commit ·
a7939d1
1
Parent(s): e93f91e
Organize search domain and strengthen type contracts
Browse filesFiles changed (11)
- backend/search/domain/projection.pyAdded+37
- backend/search_projection.py+7-37
- pyrightconfig.strict.json+1
- quality/mutation-reviews/mutation-equivalent-search-projection.json+2-2
- scripts/check_search_words_mutation.py+13-7
- static/search/requests/application/response-store.js+1-1
- tests/gates/test_mutation_gate_main.py+18-7
- tests/gates/test_quality_inventory.py+2-2
- tests/search/backend/test_search_projection_contract.py+7
- tests/search/backend/test_search_projection_mutation_contract.py+1-1
- typings/search-response-store.d.ts+2-2
12345678910111213141516171819202122232425262728293031323334353637"""Project search records using caller-owned link and path builders."""from __future__ import annotations
from collections.abc import Callable, Iterable, Mappingfrom typing import cast
SearchRecord = dict[str, object]RecordUrlBuilder = Callable[[SearchRecord], str]
def public_record(record: SearchRecord, build_link: RecordUrlBuilder, build_path: RecordUrlBuilder) -> SearchRecord: item = { key: value for key, value in cast(Mapping[object, object], record).items() if isinstance(key, str) and not key.startswith("_") } item.setdefault("Repo", "") item.setdefault("File", "") item.setdefault("Extension", "") item.setdefault("Folder", []) item.setdefault("Size", "") item.setdefault("HasTxt", False) item["Link"] = record.get("Link") or build_link(record) item["Path"] = record.get("Path") or build_path(record) return item
def trim_results(raw: Iterable[SearchRecord], project: Callable[[SearchRecord], SearchRecord]) -> list[SearchRecord]: # Fixed field reads avoid a per-record key loop. Keep their order, defaults # and per-record projection boundary: callers may supply custom mappings. return [ {"Repo": public.get("Repo", ""), "File": public.get("File", ""), "Extension": public.get("Extension", ""), "Link": public.get("Link", ""), "Path": public.get("Path", ""), "Folder": public.get("Folder", []), "Size": public.get("Size", ""), "HasTxt": public.get("HasTxt", "")} for public in (project(record) for record in raw) ]12345678910111213141516171819202122232425262728293031323334353637"""Project search records using caller-owned link and path builders."""from __future__ import annotationsfrom collections.abc import Callable, Iterable, Mappingfrom typing import castSearchRecord = dict[str, object]RecordUrlBuilder = Callable[[SearchRecord], str]def public_record(record: SearchRecord, build_link: RecordUrlBuilder, build_path: RecordUrlBuilder) -> SearchRecord:item = {key: valuefor key, value in cast(Mapping[object, object], record).items()if isinstance(key, str) and not key.startswith("_")}item.setdefault("Repo", "")item.setdefault("File", "")item.setdefault("Extension", "")item.setdefault("Folder", [])item.setdefault("Size", "")item.setdefault("HasTxt", False)item["Link"] = record.get("Link") or build_link(record)item["Path"] = record.get("Path") or build_path(record)return itemdef trim_results(raw: Iterable[SearchRecord], project: Callable[[SearchRecord], SearchRecord]) -> list[SearchRecord]:# Fixed field reads avoid a per-record key loop. Keep their order, defaults# and per-record projection boundary: callers may supply custom mappings.return [{"Repo": public.get("Repo", ""), "File": public.get("File", ""),"Extension": public.get("Extension", ""), "Link": public.get("Link", ""),"Path": public.get("Path", ""), "Folder": public.get("Folder", []),"Size": public.get("Size", ""), "HasTxt": public.get("HasTxt", "")}for public in (project(record) for record in raw)]1234567"""Compatibility exports for search projection."""from backend.search.domain.projection import (RecordUrlBuilder as RecordUrlBuilder,SearchRecord as SearchRecord,public_record as public_record,trim_results as trim_results,)
27 unmodified lines28293031323327 unmodified lines"backend/search/application/cached.py","backend/search/domain/__init__.py","backend/search/domain/ordering.py","backend/search/http/__init__.py","backend/search/http/schemas.py","backend/search/http/responses.py",27 unmodified lines2829303132333427 unmodified lines"backend/search/application/cached.py","backend/search/domain/__init__.py","backend/search/domain/ordering.py","backend/search/domain/projection.py","backend/search/http/__init__.py","backend/search/http/schemas.py","backend/search/http/responses.py",
12345678910{"tool": "mutmut 3.8.1","source": "backend/search_projection.py","source_sha256": "4113f825a0da936fdee125e304ffd8e611c50671947b6f517f3fc45e454ba23a","scope": "Review covers observable results, exceptions and callback behavior for ordinary built-in mappings and records. It excludes monkeypatching typing.cast, tracing and reflection. This is an equivalent survivor within this scope, not a killed mutation.","equivalent": {"backend.search_projection.x_public_record__mutmut_2": {"sha256": "0a3fec0b966f9d0a3c2251e60c1387b3bacd23d8485f939fd90ebd59f28f423b","rationale": "Only the type argument to typing.cast changes; with the standard cast implementation it returns the original record unchanged. Evaluating the type expression is outside the stated scope."}12345678910{"tool": "mutmut 3.8.1","source": "backend/search/domain/projection.py","source_sha256": "4113f825a0da936fdee125e304ffd8e611c50671947b6f517f3fc45e454ba23a","scope": "Review covers observable results, exceptions and callback behavior for ordinary built-in mappings and records. It excludes monkeypatching typing.cast, tracing and reflection. This is an equivalent survivor within this scope, not a killed mutation.","equivalent": {"backend.search.domain.projection.x_public_record__mutmut_2": {"sha256": "0a3fec0b966f9d0a3c2251e60c1387b3bacd23d8485f939fd90ebd59f28f423b","rationale": "Only the type argument to typing.cast changes; with the standard cast implementation it returns the original record unchanged. Evaluating the type expression is outside the stated scope."}
160 unmodified lines1611621631641651661671681691701711721731 unmodified line17517617717817918018113 unmodified lines1951961971981992002013 unmodified lines205206207208209210211212213160 unmodified linesparser.add_argument("--module", choices=tuple(SPECS), default="search_words")module = parser.parse_args().moduletest_name, selected, dependencies = SPECS[module]source = ROOT / "backend" / f"{module}.py"test = ROOT / "tests" / test_nameequivalent = ROOT / "quality/mutation-reviews" / f"mutation-equivalent-{module.replace('_', '-')}.json"review = json.loads(equivalent.read_text())source_hash = hashlib.sha256(source.read_bytes()).hexdigest()if (version("mutmut") != TOOL_VERSION or review.get("tool") != f"mutmut {TOOL_VERSION}"or review.get("source") != f"backend/{module}.py" or review.get("source_sha256") != source_hash):print("Mutation equivalent review must match the exact source and tool version", file=sys.stderr)return 1with tempfile.TemporaryDirectory(prefix=f"reader-{module}-mutation-") as directory:1 unmodified line(temp / "backend").mkdir()(temp / "tests").mkdir()shutil.copyfile(ROOT / "backend/__init__.py", temp / "backend/__init__.py")shutil.copyfile(source, temp / "backend" / f"{module}.py")for dependency in dependencies:shutil.copyfile(ROOT / "backend" / dependency, temp / "backend" / dependency)target_test = temp / "tests" / test_name13 unmodified linesif module == "search_indexes" else f"tests/{test_name}"])(temp / "pyproject.toml").write_text('[tool.mutmut]\nsource_paths = ["backend/"]\n'+ f'only_mutate = ["backend/{module}.py"]\n'+ ('also_copy = ["static/"]\n' if module == "record_metadata" else '')+ 'pytest_add_cli_args_test_selection = ' + json.dumps(selections) + '\n'+ 'use_git_change_detection = false\nuse_setproctitle = false\n')3 unmodified linescommand = [sys.executable, "-B", "-m", "mutmut", *args]subprocess.run(command, cwd=temp, env=env, check=True, timeout=600) # noqa: S603stats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text())meta = json.loads((temp / "mutants/backend" / f"{module}.py.meta").read_text())generated = (temp / "mutants/backend" / f"{module}.py").read_text()functions = generated_mutations(module, generated)generated_keys = set(functions)hashes = {}for key, code in meta["exit_code_by_key"].items():160 unmodified lines1611621631641651661671681691701711721731741 unmodified line17617717817918018118218318418518618713 unmodified lines2012022032042052062073 unmodified lines211212213214215216217218219160 unmodified linesparser.add_argument("--module", choices=tuple(SPECS), default="search_words")module = parser.parse_args().moduletest_name, selected, dependencies = SPECS[module]module_path = "search/domain/projection" if module == "search_projection" else modulesource = ROOT / "backend" / f"{module_path}.py"test = ROOT / "tests" / test_nameequivalent = ROOT / "quality/mutation-reviews" / f"mutation-equivalent-{module.replace('_', '-')}.json"review = json.loads(equivalent.read_text())source_hash = hashlib.sha256(source.read_bytes()).hexdigest()if (version("mutmut") != TOOL_VERSION or review.get("tool") != f"mutmut {TOOL_VERSION}"or review.get("source") != f"backend/{module_path}.py" or review.get("source_sha256") != source_hash):print("Mutation equivalent review must match the exact source and tool version", file=sys.stderr)return 1with tempfile.TemporaryDirectory(prefix=f"reader-{module}-mutation-") as directory:1 unmodified line(temp / "backend").mkdir()(temp / "tests").mkdir()shutil.copyfile(ROOT / "backend/__init__.py", temp / "backend/__init__.py")target_source = temp / "backend" / f"{module_path}.py"target_source.parent.mkdir(parents=True, exist_ok=True)if module == "search_projection":for package in ("search", "search/domain"):shutil.copyfile(ROOT / "backend" / package / "__init__.py", temp / "backend" / package / "__init__.py")shutil.copyfile(source, target_source)for dependency in dependencies:shutil.copyfile(ROOT / "backend" / dependency, temp / "backend" / dependency)target_test = temp / "tests" / test_name13 unmodified linesif module == "search_indexes" else f"tests/{test_name}"])(temp / "pyproject.toml").write_text('[tool.mutmut]\nsource_paths = ["backend/"]\n'+ f'only_mutate = ["backend/{module_path}.py"]\n'+ ('also_copy = ["static/"]\n' if module == "record_metadata" else '')+ 'pytest_add_cli_args_test_selection = ' + json.dumps(selections) + '\n'+ 'use_git_change_detection = false\nuse_setproctitle = false\n')3 unmodified linescommand = [sys.executable, "-B", "-m", "mutmut", *args]subprocess.run(command, cwd=temp, env=env, check=True, timeout=600) # noqa: S603stats = json.loads((temp / "mutants/mutmut-cicd-stats.json").read_text())meta = json.loads((temp / "mutants/backend" / f"{module_path}.py.meta").read_text())generated = (temp / "mutants/backend" / f"{module_path}.py").read_text()functions = generated_mutations(module_path.replace("/", "."), generated)generated_keys = set(functions)hashes = {}for key, code in meta["exit_code_by_key"].items():
11 unmodified lines1213141516171811 unmodified lines/** @type {ReturnType<typeof setTimeout> | null} */let writeTimer = null;/** @template T @param {T} data @returns {T} */function cloneSearchData(data) {const page = /** @type {T & {results?: unknown[], total?: unknown, page?: unknown, page_size?: unknown}} */ (data);if (!page || !Array.isArray(page.results)) return data;11 unmodified lines1213141516171811 unmodified lines/** @type {ReturnType<typeof setTimeout> | null} */let writeTimer = null;/** @template {VoiceOfMLSearchWindowPageData} T @param {T} data @returns {T} */function cloneSearchData(data) {const page = /** @type {T & {results?: unknown[], total?: unknown, page?: unknown, page_size?: unknown}} */ (data);if (!page || !Array.isArray(page.results)) return data;
57 unmodified lines585960616263644 unmodified lines697071727374757677787980818283848586878821 unmodified lines11011111211311411511611711811912012157 unmodified linesself.assertEqual([path.relative_to(cwd) for path in (Path(cwd) / 'static').rglob('*')if path.is_file()], [fixture])self.assertEqual({path.name for path in Path(cwd).iterdir()}, expected_entries)for rel in ('backend/__init__.py', f'backend/{self.module}.py',f'tests/{gate.SPECS[self.module][0]}'):self.assertEqual((Path(cwd) / rel).read_bytes(), (self.root / rel).read_bytes())self.assertEqual((Path(cwd) / 'tests/__init__.py').read_bytes(), b'')4 unmodified linesself.assertEqual((Path(cwd) / 'tests/support/reader-contract-vectors.json').read_bytes(),(self.root / 'tests/support/reader-contract-vectors.json').read_bytes())if command[-1] == 'export-cicd-stats':folder = Path(cwd) / 'mutants/backend'folder.mkdir(parents=True)stats = {'total': self.count, 'killed': int(self.outcome == 1),'survived': int(self.outcome == 0), **dict.fromkeys(gate.EMPTY_STATUSES, 0)}if self.unknown_status:stats[self.unknown_status] = 1(folder.parent / 'mutmut-cicd-stats.json').write_text(json.dumps(stats))meta = {'exit_code_by_key': {f'backend.{self.module}.x_example__mutmut_1': self.outcome}}if self.include_timings:timings = {'durations_by_key': self.durations, 'estimated_durations_by_key': self.estimates}meta.update({key: value for key, value in timings.items()if self.timing_fields is None or key in self.timing_fields})(folder / f'{self.module}.py.meta').write_text(json.dumps(meta))(folder / f'{self.module}.py').write_text(self.generated)return Noneif self.reviewed:21 unmodified linesself.args = ['--module', module]test_name, _, dependencies = gate.SPECS[module]source = b'def synthetic(value):\n return value\n'(self.root / 'backend' / f'{module}.py').write_bytes(source)target_test = self.root / 'tests' / test_nametarget_test.parent.mkdir(parents=True, exist_ok=True)target_test.write_text('def test_fixture(): pass\n')(self.root / 'quality/mutation-reviews' / f'mutation-equivalent-{module.replace("_", "-")}.json').write_text(json.dumps({'tool': 'mutmut 3.8.1', 'source': f'backend/{module}.py','source_sha256': hashlib.sha256(source).hexdigest(), 'equivalent': {}}))for dependency in dependencies:(self.root / 'backend' / dependency).write_text(f'# synthetic dependency {dependency}\n')57 unmodified lines58596061626364656667684 unmodified lines73747576777879808182838485868788899091929321 unmodified lines11511611711811912012112212312412512612712812913013113257 unmodified linesself.assertEqual([path.relative_to(cwd) for path in (Path(cwd) / 'static').rglob('*')if path.is_file()], [fixture])self.assertEqual({path.name for path in Path(cwd).iterdir()}, expected_entries)module_path = 'search/domain/projection' if self.module == 'search_projection' else self.moduleif self.module == 'search_projection':self.assertEqual(self.configurations[-1]['tool']['mutmut']['only_mutate'],['backend/search/domain/projection.py'])for rel in ('backend/__init__.py', f'backend/{module_path}.py',f'tests/{gate.SPECS[self.module][0]}'):self.assertEqual((Path(cwd) / rel).read_bytes(), (self.root / rel).read_bytes())self.assertEqual((Path(cwd) / 'tests/__init__.py').read_bytes(), b'')4 unmodified linesself.assertEqual((Path(cwd) / 'tests/support/reader-contract-vectors.json').read_bytes(),(self.root / 'tests/support/reader-contract-vectors.json').read_bytes())if command[-1] == 'export-cicd-stats':module_path = 'search/domain/projection' if self.module == 'search_projection' else self.modulefolder = Path(cwd) / 'mutants/backend'(folder / module_path).parent.mkdir(parents=True)stats = {'total': self.count, 'killed': int(self.outcome == 1),'survived': int(self.outcome == 0), **dict.fromkeys(gate.EMPTY_STATUSES, 0)}if self.unknown_status:stats[self.unknown_status] = 1(folder.parent / 'mutmut-cicd-stats.json').write_text(json.dumps(stats))meta = {'exit_code_by_key': {f'backend.{module_path.replace("/", ".")}.x_example__mutmut_1': self.outcome}}if self.include_timings:timings = {'durations_by_key': self.durations, 'estimated_durations_by_key': self.estimates}meta.update({key: value for key, value in timings.items()if self.timing_fields is None or key in self.timing_fields})(folder / f'{module_path}.py.meta').write_text(json.dumps(meta))(folder / f'{module_path}.py').write_text(self.generated)return Noneif self.reviewed:21 unmodified linesself.args = ['--module', module]test_name, _, dependencies = gate.SPECS[module]source = b'def synthetic(value):\n return value\n'module_path = 'search/domain/projection' if module == 'search_projection' else modulesource_file = self.root / 'backend' / f'{module_path}.py'source_file.parent.mkdir(parents=True, exist_ok=True)source_file.write_bytes(source)if module == 'search_projection':for package in ('search', 'search/domain'):(self.root / 'backend' / package / '__init__.py').write_text('')target_test = self.root / 'tests' / test_nametarget_test.parent.mkdir(parents=True, exist_ok=True)target_test.write_text('def test_fixture(): pass\n')(self.root / 'quality/mutation-reviews' / f'mutation-equivalent-{module.replace("_", "-")}.json').write_text(json.dumps({'tool': 'mutmut 3.8.1', 'source': f'backend/{module_path}.py','source_sha256': hashlib.sha256(source).hexdigest(), 'equivalent': {}}))for dependency in dependencies:(self.root / 'backend' / dependency).write_text(f'# synthetic dependency {dependency}\n')
1519 unmodified lines1520152115221523152415251526152715281529153015311519 unmodified linesroot = Path(__file__).resolve().parents[2]review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-search-projection.json").read_text())self.assertEqual(review["tool"], "mutmut 3.8.1")self.assertEqual(review["source"], "backend/search_projection.py")self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest())self.assertTrue(review["scope"])for name, entry in review["equivalent"].items():with self.subTest(mutant=name):self.assertTrue(name.startswith("backend.search_projection."))self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$")self.assertTrue(entry["rationale"])1519 unmodified lines1520152115221523152415251526152715281529153015311519 unmodified linesroot = Path(__file__).resolve().parents[2]review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-search-projection.json").read_text())self.assertEqual(review["tool"], "mutmut 3.8.1")self.assertEqual(review["source"], "backend/search/domain/projection.py")self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest())self.assertTrue(review["scope"])for name, entry in review["equivalent"].items():with self.subTest(mutant=name):self.assertTrue(name.startswith("backend.search.domain.projection."))self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$")self.assertTrue(entry["rationale"])
2 unmodified lines345678910112 unmodified linesfrom unittest.mock import patchfrom backend import app, search_projectionclass SearchProjectionContractTests(TestCase):def test_public_projection_filters_private_keys_but_preserves_explicit_values(self):folder = ["chapter"]original = {"Repo": "A", "File": "name", "Folder": folder, "Size": None,2 unmodified lines34567891011121314151617182 unmodified linesfrom unittest.mock import patchfrom backend import app, search_projectionfrom backend.search.domain import projectionclass SearchProjectionContractTests(TestCase):def test_compatibility_exports_are_canonical(self):self.assertIs(search_projection.public_record, projection.public_record)self.assertIs(search_projection.trim_results, projection.trim_results)self.assertIs(search_projection.SearchRecord, projection.SearchRecord)self.assertIs(search_projection.RecordUrlBuilder, projection.RecordUrlBuilder)def test_public_projection_filters_private_keys_but_preserves_explicit_values(self):folder = ["chapter"]original = {"Repo": "A", "File": "name", "Folder": folder, "Size": None,
1234567"""Pure projection contracts for the complete isolated mutation inventory."""import unittestfrom backend import search_projection as projectionclass SearchProjectionMutationContractTests(unittest.TestCase):1234567"""Pure projection contracts for the complete isolated mutation inventory."""import unittestfrom backend.search.domain import projectionclass SearchProjectionMutationContractTests(unittest.TestCase):
1 unmodified line2345678910111213141 unmodified linelimit: number;ttl: number;getSearchViewKey(): string;rememberSearchPageMetadata(data: unknown): void;}interface SearchResponseStore {cache: BoundedResponseCache<{time: number; data: VoiceOfMLSearchWindowPageData}>;pendingWrites: Map<string, {data: VoiceOfMLSearchWindowPageData; viewKey: string; acquiredAt: number}>;identities: WeakMap<object, object>;cloneSearchData<T>(data: T): T;getCachedSearchResponse(key: string): VoiceOfMLSearchWindowPageData | null;cancelPendingSearchCacheWrites(): void;setCachedSearchResponse(key: string, data: VoiceOfMLSearchWindowPageData, defer?: boolean, acquiredAt?: number): void;1 unmodified line2345678910111213141 unmodified linelimit: number;ttl: number;getSearchViewKey(): string;rememberSearchPageMetadata(data: VoiceOfMLSearchWindowPageData): void;}interface SearchResponseStore {cache: BoundedResponseCache<{time: number; data: VoiceOfMLSearchWindowPageData}>;pendingWrites: Map<string, {data: VoiceOfMLSearchWindowPageData; viewKey: string; acquiredAt: number}>;identities: WeakMap<object, object>;cloneSearchData<T extends VoiceOfMLSearchWindowPageData>(data: T): T;getCachedSearchResponse(key: string): VoiceOfMLSearchWindowPageData | null;cancelPendingSearchCacheWrites(): void;setCachedSearchResponse(key: string, data: VoiceOfMLSearchWindowPageData, defer?: boolean, acquiredAt?: number): void;
backend/search/domain/projection.pyAdded+37
backend/search_projection.py+7-37
pyrightconfig.strict.json+1
quality/mutation-reviews/mutation-equivalent-search-projection.json+2-2
scripts/check_search_words_mutation.py+13-7
static/search/requests/application/response-store.js+1-1
tests/gates/test_mutation_gate_main.py+18-7
tests/gates/test_quality_inventory.py+2-2
tests/search/backend/test_search_projection_contract.py+7
tests/search/backend/test_search_projection_mutation_contract.py+1-1
typings/search-response-store.d.ts+2-2