Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s
CI / tests (pull_request) Successful in 3m43s
This commit is contained in:
@@ -6,10 +6,10 @@ import errno
|
||||
import gzip
|
||||
import os
|
||||
import pathlib
|
||||
import typing
|
||||
import zlib
|
||||
|
||||
from failure import Failure
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
SUFFIX = ".gz"
|
||||
|
||||
@@ -43,20 +43,20 @@ def stored_glob(folder: pathlib.Path, pattern: str) -> list[pathlib.Path]:
|
||||
return sorted({*folder.glob(pattern), *(path.with_name(path.name.removesuffix(SUFFIX)) for path in folder.glob(pattern + SUFFIX))})
|
||||
|
||||
|
||||
def compress(path: pathlib.Path) -> Failure | None:
|
||||
"""Replaces path with its gzip, which keeps path's times: writes the gzip, reads it back, and removes path only once it reads back path's bytes. A failure keeps path."""
|
||||
def compress(path: pathlib.Path, *, pack: typing.Callable[..., bytes], replace: typing.Callable[[pathlib.Path, bytes], Failure | None], sync: typing.Callable[[int], None]) -> Failure | None:
|
||||
"""Replaces path with its gzip, which keeps path's times: writes the gzip, reads it back, and removes path only once it reads back path's bytes. A failure keeps path. pack compresses as gzip.compress does, replace writes as replace_file does, and sync flushes as os.fsync does."""
|
||||
packed = gzipped(path)
|
||||
try:
|
||||
before = path.stat()
|
||||
data = path.read_bytes()
|
||||
if unwritten := replace_file(packed, gzip.compress(data, mtime=0)):
|
||||
if unwritten := replace(packed, pack(data, mtime=0)):
|
||||
return Failure(f"could not compress {path}: {unwritten.reason}")
|
||||
if gzip.decompress(packed.read_bytes()) != data:
|
||||
return Failure(f"could not compress {path}: {packed} reads back other bytes")
|
||||
os.utime(packed, ns=(before.st_atime_ns, before.st_mtime_ns))
|
||||
# On disk before the plain file goes, so a crash cannot leave an empty gzip in its place.
|
||||
synced(packed)
|
||||
synced(packed.parent)
|
||||
synced(packed, sync)
|
||||
synced(packed.parent, sync)
|
||||
after = path.stat()
|
||||
# Written while it compressed: the plain file keeps the newer bytes, which readers prefer, and a later run compresses them.
|
||||
if (after.st_size, after.st_mtime_ns) == (before.st_size, before.st_mtime_ns):
|
||||
@@ -66,10 +66,10 @@ def compress(path: pathlib.Path) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def synced(path: pathlib.Path) -> None:
|
||||
def synced(path: pathlib.Path, sync: typing.Callable[[int], None]) -> None:
|
||||
handle = os.open(path, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(handle)
|
||||
sync(handle)
|
||||
finally:
|
||||
os.close(handle)
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
"""What the suites that compress a file share: compress, bound to what really compresses, writes and flushes."""
|
||||
import functools
|
||||
import gzip
|
||||
import os
|
||||
|
||||
from text_files import compressed
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
# A test names pack, replace or sync to swap that one.
|
||||
compress = functools.partial(compressed.compress, pack=gzip.compress, replace=replace_file, sync=os.fsync)
|
||||
@@ -1,6 +1,5 @@
|
||||
import errno
|
||||
import gzip
|
||||
from unittest import mock
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
@@ -9,6 +8,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from text_files.doubles import compress
|
||||
from text_files import compressed
|
||||
from failure import Failure
|
||||
|
||||
@@ -19,7 +19,7 @@ class Compress(unittest.TestCase):
|
||||
plain = pathlib.Path(root, "t.jsonl")
|
||||
plain.write_bytes(b'{"a": 1}\n')
|
||||
os.utime(plain, (1000, 2000))
|
||||
self.assertIsNone(compressed.compress(plain))
|
||||
self.assertIsNone(compress(plain))
|
||||
self.assertFalse(plain.exists())
|
||||
packed = pathlib.Path(root, "t.jsonl.gz")
|
||||
# A gzip header's own time is 0, so compressing the same bytes twice writes the same file.
|
||||
@@ -37,31 +37,28 @@ class Compress(unittest.TestCase):
|
||||
synced.append((os.readlink(f"/proc/self/fd/{handle}"), plain.exists()))
|
||||
fsync(handle)
|
||||
|
||||
with mock.patch.object(compressed.os, "fsync", record):
|
||||
self.assertIsNone(compressed.compress(plain))
|
||||
self.assertIsNone(compress(plain, sync=record))
|
||||
self.assertEqual(synced, [(os.path.realpath(f"{plain}.gz"), True), (os.path.realpath(root), True)])
|
||||
|
||||
def test_a_gzip_it_cannot_write_keeps_the_original_and_says_why(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
plain = pathlib.Path(root, "t.jsonl")
|
||||
plain.write_bytes(b"kept\n")
|
||||
with mock.patch.object(compressed, "replace_file", return_value=Failure("disk full")):
|
||||
self.assertEqual(compressed.compress(plain), Failure(f"could not compress {plain}: disk full"))
|
||||
self.assertEqual(compress(plain, replace=lambda path, data: Failure("disk full")), Failure(f"could not compress {plain}: disk full"))
|
||||
self.assertEqual(plain.read_bytes(), b"kept\n")
|
||||
|
||||
def test_a_file_it_cannot_read_fails_naming_it(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = pathlib.Path(root, "t.jsonl")
|
||||
folder.mkdir()
|
||||
failed = compressed.compress(folder)
|
||||
failed = compress(folder)
|
||||
self.assertTrue(failed.reason.startswith(f"could not compress {folder}: [Errno {errno.EISDIR}]"), failed.reason)
|
||||
|
||||
def test_a_copy_that_reads_back_other_bytes_keeps_the_original_and_fails(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
plain = pathlib.Path(root, "t.jsonl")
|
||||
plain.write_bytes(b"kept\n")
|
||||
with mock.patch.object(compressed.gzip, "compress", return_value=gzip.compress(b"other\n")):
|
||||
failed = compressed.compress(plain)
|
||||
failed = compress(plain, pack=lambda data, **kwargs: gzip.compress(b"other\n"))
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn(str(plain), failed.reason)
|
||||
self.assertEqual(plain.read_bytes(), b"kept\n")
|
||||
@@ -70,15 +67,12 @@ class Compress(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
plain = pathlib.Path(root, "t.jsonl")
|
||||
plain.write_bytes(b"one\n")
|
||||
packing = compressed.gzip.compress
|
||||
|
||||
def grow_meanwhile(data, **kwargs):
|
||||
with open(plain, "ab") as handle:
|
||||
handle.write(b"two\n")
|
||||
return packing(data, **kwargs)
|
||||
return gzip.compress(data, **kwargs)
|
||||
|
||||
with mock.patch.object(compressed.gzip, "compress", grow_meanwhile):
|
||||
self.assertIsNone(compressed.compress(plain))
|
||||
self.assertIsNone(compress(plain, pack=grow_meanwhile))
|
||||
self.assertEqual(plain.read_bytes(), b"one\ntwo\n")
|
||||
self.assertEqual(compressed.read_stored(plain), b"one\ntwo\n")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user