Skip to content

Commit 252f688

Browse files
alexmalyshevmeta-codesync[bot]
authored andcommitted
Fix test_strict_compile depending on a warm __strict__ pyc
Summary: `test_strict_compile` patched `StrictSourceFileLoader.source_to_code` to return `None` class-wide, to prove that `a.py` is loaded from the pyc built by `strict_compile()` rather than recompiled. But `a.py` executes `import __strict__`, which goes through that same patched loader, so the test only passes when `__strict__` already has a valid cached pyc. Under `ctr` the whole module runs in one process and an earlier test warms `__strict__/__pycache__/__init__.cpython-314.strict.pyc`, so the test passes. Under `buck test` each test method gets its own process against a cold link-tree, so it always failed with: ImportError: Cannot import module __strict__; get_code() returned None Scope the patch to `a.py` so the modules its body pulls in still compile normally. Reviewed By: yoney Differential Revision: D116071905 fbshipit-source-id: 2e93b833ff3d1e4c1a3a9d8f21884e142f4d3f1c
1 parent 51a4794 commit 252f688

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

  • cinderx/PythonLib/test_cinderx/test_compiler/test_strict

cinderx/PythonLib/test_cinderx/test_compiler/test_strict/test_loader.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from importlib.util import cache_from_source
2323
from os import path
2424
from py_compile import PycInvalidationMode
25-
from types import ModuleType
25+
from types import CodeType, ModuleType
2626
from typing import cast, final, List, TYPE_CHECKING, TypeVar
2727
from unittest.mock import patch
2828

@@ -515,10 +515,23 @@ def test_strict_compile(self) -> None:
515515
fn = self.sbx.write_file("a.py", "import __strict__\nx = 2")
516516
strict_compile(str(fn), cache_from_source(fn))
517517

518-
# patch source_to_code on the loader to ensure we are loading from pyc
519-
with patch.object(
520-
StrictSourceFileLoader, "source_to_code", lambda *a, **kw: None
521-
):
518+
orig_source_to_code = StrictSourceFileLoader.source_to_code
519+
520+
# Break compilation of 'a.py' only, so the test fails if it is not
521+
# loaded from the pyc. Modules pulled in by executing it, notably
522+
# `__strict__` itself, still have to compile normally.
523+
def source_to_code(
524+
loader: StrictSourceFileLoader,
525+
data: bytes | str,
526+
path: str,
527+
*,
528+
_optimize: int = -1,
529+
) -> CodeType | None:
530+
if path == str(fn):
531+
return None
532+
return orig_source_to_code(loader, data, path, _optimize=_optimize)
533+
534+
with patch.object(StrictSourceFileLoader, "source_to_code", source_to_code):
522535
mod = self.sbx.strict_import("a")
523536

524537
self.assertEqual(type(mod), StrictModule)

0 commit comments

Comments
 (0)