diff --git a/tests/test_world_index.py b/tests/test_world_index.py index cb65b7464..0ee573d34 100644 --- a/tests/test_world_index.py +++ b/tests/test_world_index.py @@ -942,6 +942,23 @@ class WorldIndexTest(unittest.TestCase): # Every resource field emitted by parse_resource() for this map must have a matching CSV column. self.assertEqual(set(json_row) - set(fieldnames), set()) + def test_staged_entity_report_restores_write_mode_on_replace_failure(self): + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(p, mode, **kwargs): + chmod_calls.append((str(p), mode)) + return real_chmod(p, mode, **kwargs) + + out_path = os.path.join(self.dir, "entities.jsonl") + with mock.patch.object(WI.os, "replace", side_effect=OSError("replace failed")), \ + mock.patch.object(WI.os, "chmod", side_effect=track_chmod): + with self.assertRaisesRegex(OSError, "replace failed"): + with WI._staged_entity_report(out_path): + pass + + self.assertTrue(any(mode == 0o600 for _, mode in chmod_calls), chmod_calls) + def setUpModule(): # The tools' main() prints its summary JSON; keep it out of the test log (tests that check it redirect again). diff --git a/tools/world_index.py b/tools/world_index.py index d6427a45b..8b1044e9a 100644 --- a/tools/world_index.py +++ b/tools/world_index.py @@ -39,6 +39,9 @@ import tempfile import zlib from contextlib import contextmanager +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from file_mode import published_mode + # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. _TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) if _TOOLS_DIR not in sys.path: @@ -788,15 +791,22 @@ def _staged_entity_report(path): try: with open(staged, "w", encoding="utf-8", newline="\n") as handle: yield EntityRows(handle) - if mode is not None: - os.chmod(staged, mode & 0o777) + try: + os.chmod(staged, published_mode(destination)) + except OSError: + pass os.replace(staged, destination) finally: if os.path.exists(staged): - if os.name == "nt": - os.chmod(staged, stat.S_IWRITE) + try: + os.chmod(staged, 0o600) + except OSError: + pass os.unlink(staged) - os.rmdir(directory) + try: + os.rmdir(directory) + except OSError: + pass def main(argv=None):