|
| 1 | +"""Unit tests for the sentinel-cleanup and syntax-validation guards in osw.core. |
| 2 | +
|
| 3 | +Regression guard for #125: datamodel-code-generator uses a bare |
| 4 | +`UNDEFINED = object()` sentinel with `is` identity checks. oold's merge_deep |
| 5 | +deep-copies schema dicts during allOf composition, which clones that sentinel |
| 6 | +into a look-alike object, defeating the identity guard, so the generator |
| 7 | +repr's it into source (see oold.generator.Generator.generate() for oold's own |
| 8 | +workaround). _fetch_schema used to write that content straight to entity.py |
| 9 | +and reload it, raising SyntaxError and poisoning every later `import |
| 10 | +osw.core` in the process. |
| 11 | +
|
| 12 | +These tests exercise the extracted helpers directly, fully offline, and |
| 13 | +never call the real (wiki- and network-backed) `_fetch_schema`. |
| 14 | +""" |
| 15 | + |
| 16 | +import ast |
| 17 | +import importlib |
| 18 | +import sys |
| 19 | + |
| 20 | +import pytest |
| 21 | + |
| 22 | +from osw.core import ( |
| 23 | + ensure_valid_python_source, |
| 24 | + reload_module_or_restore, |
| 25 | + remove_unserializable_default_sentinels, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +@pytest.fixture |
| 30 | +def throwaway_module(tmp_path): |
| 31 | + """An importable module on disk, cleaned out of sys.modules afterwards""" |
| 32 | + name = "osw_test_throwaway_model" |
| 33 | + path = tmp_path / f"{name}.py" |
| 34 | + path.write_text("VALUE = 1\n", encoding="utf-8") |
| 35 | + sys.path.insert(0, str(tmp_path)) |
| 36 | + try: |
| 37 | + yield importlib.import_module(name), path |
| 38 | + finally: |
| 39 | + sys.path.remove(str(tmp_path)) |
| 40 | + sys.modules.pop(name, None) |
| 41 | + |
| 42 | + |
| 43 | +def test_sentinel_default_is_rewritten_to_valid_python(): |
| 44 | + """A repr'd sentinel object breaks ast.parse until the substitution runs.""" |
| 45 | + bad = ( |
| 46 | + "risk_assessment: RiskAssessmentProcess | None = Field(" |
| 47 | + "default_factory=lambda :<object object at 0x000001A2B3C4D5E6>)\n" |
| 48 | + ) |
| 49 | + with pytest.raises(SyntaxError): |
| 50 | + ast.parse(bad) |
| 51 | + |
| 52 | + fixed = remove_unserializable_default_sentinels(bad) |
| 53 | + |
| 54 | + assert "<object object at" not in fixed |
| 55 | + ast.parse(fixed) # must not raise |
| 56 | + |
| 57 | + |
| 58 | +def test_sentinel_wrapped_in_a_parse_obj_call_is_rewritten(): |
| 59 | + """The shape actually reported in #125, where the sentinel sits inside a |
| 60 | + `parse_obj(...)` call and the field carries further keyword arguments. |
| 61 | +
|
| 62 | + oold's own regex stops at the first `)` after the address, which is the |
| 63 | + one belonging to `parse_obj(`, and so leaves a dangling `)` behind. |
| 64 | + """ |
| 65 | + bad = ( |
| 66 | + "risk_assessment: RiskAssessmentProcess | None = Field(" |
| 67 | + "default_factory=lambda :RiskAssessmentProcess.parse_obj(" |
| 68 | + "<object object at 0x000001A2B3C4D5E6>), options={'a': 1})\n" |
| 69 | + ) |
| 70 | + with pytest.raises(SyntaxError): |
| 71 | + ast.parse(bad) |
| 72 | + |
| 73 | + fixed = remove_unserializable_default_sentinels(bad) |
| 74 | + |
| 75 | + assert "<object object at" not in fixed |
| 76 | + assert "options={'a': 1}" in fixed # trailing kwargs are preserved |
| 77 | + ast.parse(fixed) # must not raise |
| 78 | + |
| 79 | + |
| 80 | +def test_legitimate_default_factory_lambda_is_not_mangled(): |
| 81 | + """A normal `default_factory=lambda: uuid4()` must survive untouched.""" |
| 82 | + legit = "id: UUID = Field(default_factory=lambda: uuid4())\n" |
| 83 | + |
| 84 | + assert remove_unserializable_default_sentinels(legit) == legit |
| 85 | + |
| 86 | + |
| 87 | +def test_ensure_valid_python_source_accepts_valid_source(): |
| 88 | + ensure_valid_python_source("class Foo:\n pass\n", "entity.py") # no raise |
| 89 | + |
| 90 | + |
| 91 | +def test_ensure_valid_python_source_raises_with_a_useful_message(): |
| 92 | + bad = "class Foo(:\n pass\n" |
| 93 | + |
| 94 | + with pytest.raises(SyntaxError) as exc_info: |
| 95 | + ensure_valid_python_source(bad, "entity.py") |
| 96 | + |
| 97 | + message = str(exc_info.value) |
| 98 | + assert "entity.py" in message |
| 99 | + assert "line 1" in message |
| 100 | + assert "class Foo(:" in message |
| 101 | + |
| 102 | + |
| 103 | +def test_validation_failure_leaves_an_existing_target_untouched(tmp_path): |
| 104 | + """Mirrors the guarded write in _fetch_schema: validation runs before the |
| 105 | + file is ever opened for writing, so a bad generation never touches the |
| 106 | + previous, valid content sitting at the target path. |
| 107 | + """ |
| 108 | + target = tmp_path / "entity.py" |
| 109 | + target.write_text("previous_valid_content = 1\n", encoding="utf-8") |
| 110 | + |
| 111 | + bad = "class Foo(:\n pass\n" |
| 112 | + |
| 113 | + with pytest.raises(SyntaxError): |
| 114 | + ensure_valid_python_source(bad, str(target)) |
| 115 | + target.write_text("corrupted", encoding="utf-8") # never reached |
| 116 | + |
| 117 | + assert target.read_text(encoding="utf-8") == "previous_valid_content = 1\n" |
| 118 | + |
| 119 | + |
| 120 | +def test_reload_restores_previous_content_when_the_new_model_cannot_import( |
| 121 | + throwaway_module, |
| 122 | +): |
| 123 | + """Syntactically valid content can still fail at import time. The file must |
| 124 | + be rolled back so later imports keep working. |
| 125 | + """ |
| 126 | + module, path = throwaway_module |
| 127 | + previous_content = path.read_text(encoding="utf-8") |
| 128 | + broken = "raise RuntimeError('not importable')\n" |
| 129 | + ast.parse(broken) # passes the syntax guard, so only the import catches it |
| 130 | + path.write_text(broken, encoding="utf-8") |
| 131 | + |
| 132 | + with pytest.raises(RuntimeError): |
| 133 | + reload_module_or_restore(module, str(path), previous_content) |
| 134 | + |
| 135 | + assert path.read_text(encoding="utf-8") == previous_content |
| 136 | + assert module.VALUE == 1 # the in-memory module works again too |
| 137 | + |
| 138 | + |
| 139 | +def test_reload_keeps_the_new_model_when_it_imports(throwaway_module): |
| 140 | + module, path = throwaway_module |
| 141 | + # the length has to differ from the original source, otherwise the pyc |
| 142 | + # cache (keyed on mtime and size) can survive the reload |
| 143 | + path.write_text("VALUE = 222\n", encoding="utf-8") |
| 144 | + |
| 145 | + reload_module_or_restore(module, str(path), "VALUE = 1\n") |
| 146 | + |
| 147 | + assert path.read_text(encoding="utf-8") == "VALUE = 222\n" |
| 148 | + assert module.VALUE == 222 |
| 149 | + |
| 150 | + |
| 151 | +def test_reload_without_previous_content_still_raises(throwaway_module): |
| 152 | + """First-ever write has nothing to roll back to, but must not fail silently.""" |
| 153 | + module, path = throwaway_module |
| 154 | + path.write_text("raise RuntimeError('not importable')\n", encoding="utf-8") |
| 155 | + |
| 156 | + with pytest.raises(RuntimeError): |
| 157 | + reload_module_or_restore(module, str(path), None) |
0 commit comments