tee-logger 6.44__tar.gz → 6.45__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tee-logger
3
- Version: 6.44
3
+ Version: 6.45
4
4
  Summary: A simple wrapper for python logger that also selectively tee logs to stdout
5
5
  Author-email: Yufei Pan <pan@zopyr.us>
6
- License: GPL-3.0-or-later
6
+ License-Expression: GPL-3.0-or-later
7
7
  Project-URL: Homepage, https://github.com/yufei-pan/Tee_Logger
8
- Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
9
8
  Classifier: Programming Language :: Python :: 3
10
9
  Classifier: Operating System :: OS Independent
11
10
  Requires-Python: >=3.6
@@ -152,7 +151,7 @@ On initialization and at each midnight rollover, `{programName}_log/` is scanned
152
151
 
153
152
  Folders with a file modified in the last 24 hours are left alone, in case another process is still writing there. A folder named like a date that is not one (`2020-13-45`) is skipped, with a message on stderr. The work runs in a background thread; the program exits only after an archive in progress is finished. `cleanup_old_logs()` runs the same maintenance synchronously.
154
153
 
155
- Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file and renamed into place, and only then is the folder deleted. If archiving fails, the folder is put back; a claim left by a crashed process is picked up again after 24 hours.
154
+ Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file, flushed to disk (fsync) and renamed into place, the directory is flushed too, and only then is the folder deleted. If archiving or the flush of the archive fails, the folder is put back; if the directory flush fails, the claim stays with the logs in it; a claim left by a crashed process is picked up again after 24 hours.
156
155
 
157
156
  ## API reference
158
157
 
@@ -194,6 +193,11 @@ python src/Tee_Logger.py -V
194
193
 
195
194
  CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
196
195
 
196
+ ## Upgrading to 6.45 from 6.44
197
+
198
+ - Packaging only: the license is declared as the SPDX expression `GPL-3.0-or-later` (no license classifier), so building from source needs setuptools 77.0.1 or later, which needs Python 3.9 or later. The code is unchanged. pip 9 (EL7, EL8) still installs the wheel; its `pip show` prints `License: None`, as it cannot read the new field.
199
+ - Compressing a day's logs flushes the archive to disk before it is renamed into place, and the log directory after, before the day's logs are deleted. Before, a crash or hard reset before the kernel wrote the archive back, often tens of seconds after a compression, could leave an empty or short `.tar.xz` and no logs (possible on XFS, and on ext4 for a new name). Where the file system cannot sync (some FUSE mounts), or the directory cannot be opened for it (a mode 0300 directory), or on Windows, the flush is skipped, as before. A disk that refuses the flush keeps the logs and reports `Failed to sync` or `Failed to compress folder` on stderr; a later cleanup tries again.
200
+
197
201
  ## Upgrading to 6.44 from 6.43
198
202
 
199
203
  - Compressed logs are written as one whole gzip member (xz or bz2 stream, zstd frame) per flush. In 6.43 a gzip or zstd log could not be read past the point where a run was killed, once a restarted run or a second process with the same `programName` appended to the same day's file; such a file now stays readable. The cost: gzip and zstd logs with frequent `WARNING`+ records, or with `flush_interval=0`, are larger (see the limitations above). xz and bz2 logs are unchanged.
@@ -1,20 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: tee-logger
3
- Version: 6.44
4
- Summary: A simple wrapper for python logger that also selectively tee logs to stdout
5
- Author-email: Yufei Pan <pan@zopyr.us>
6
- License: GPL-3.0-or-later
7
- Project-URL: Homepage, https://github.com/yufei-pan/Tee_Logger
8
- Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.6
12
- Description-Content-Type: text/markdown
13
- License-File: LICENSE
14
- Provides-Extra: dev
15
- Requires-Dist: pytest>=7.0; extra == "dev"
16
- Dynamic: license-file
17
-
18
1
  # Tee_Logger
19
2
 
20
3
  A Python logger that writes to a dated log file and optionally mirrors output to stdout with ANSI colors. Supports in-place compression, automatic log archival, and smart caller line attribution.
@@ -152,7 +135,7 @@ On initialization and at each midnight rollover, `{programName}_log/` is scanned
152
135
 
153
136
  Folders with a file modified in the last 24 hours are left alone, in case another process is still writing there. A folder named like a date that is not one (`2020-13-45`) is skipped, with a message on stderr. The work runs in a background thread; the program exits only after an archive in progress is finished. `cleanup_old_logs()` runs the same maintenance synchronously.
154
137
 
155
- Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file and renamed into place, and only then is the folder deleted. If archiving fails, the folder is put back; a claim left by a crashed process is picked up again after 24 hours.
138
+ Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file, flushed to disk (fsync) and renamed into place, the directory is flushed too, and only then is the folder deleted. If archiving or the flush of the archive fails, the folder is put back; if the directory flush fails, the claim stays with the logs in it; a claim left by a crashed process is picked up again after 24 hours.
156
139
 
157
140
  ## API reference
158
141
 
@@ -194,6 +177,11 @@ python src/Tee_Logger.py -V
194
177
 
195
178
  CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
196
179
 
180
+ ## Upgrading to 6.45 from 6.44
181
+
182
+ - Packaging only: the license is declared as the SPDX expression `GPL-3.0-or-later` (no license classifier), so building from source needs setuptools 77.0.1 or later, which needs Python 3.9 or later. The code is unchanged. pip 9 (EL7, EL8) still installs the wheel; its `pip show` prints `License: None`, as it cannot read the new field.
183
+ - Compressing a day's logs flushes the archive to disk before it is renamed into place, and the log directory after, before the day's logs are deleted. Before, a crash or hard reset before the kernel wrote the archive back, often tens of seconds after a compression, could leave an empty or short `.tar.xz` and no logs (possible on XFS, and on ext4 for a new name). Where the file system cannot sync (some FUSE mounts), or the directory cannot be opened for it (a mode 0300 directory), or on Windows, the flush is skipped, as before. A disk that refuses the flush keeps the logs and reports `Failed to sync` or `Failed to compress folder` on stderr; a later cleanup tries again.
184
+
197
185
  ## Upgrading to 6.44 from 6.43
198
186
 
199
187
  - Compressed logs are written as one whole gzip member (xz or bz2 stream, zstd frame) per flush. In 6.43 a gzip or zstd log could not be read past the point where a run was killed, once a restarted run or a second process with the same `programName` appended to the same day's file; such a file now stays readable. The cost: gzip and zstd logs with frequent `WARNING`+ records, or with `flush_interval=0`, are larger (see the limitations above). xz and bz2 logs are unchanged.
@@ -1,5 +1,7 @@
1
1
  [build-system]
2
- requires = ["setuptools>=61"]
2
+ # 77.0.1 is the first setuptools on PyPI that accepts `license` as an SPDX string (PEP 639):
3
+ # 76.1.0 rejects the string, and 77.0.0 is not on PyPI.
4
+ requires = ["setuptools>=77.0.1"]
3
5
  build-backend = "setuptools.build_meta"
4
6
 
5
7
  [project]
@@ -13,11 +15,10 @@ authors = [
13
15
  { name = "Yufei Pan", email = "pan@zopyr.us" }
14
16
  ]
15
17
  classifiers = [
16
- "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
17
18
  "Programming Language :: Python :: 3",
18
19
  "Operating System :: OS Independent"
19
20
  ]
20
- license = {text = "GPL-3.0-or-later"}
21
+ license = "GPL-3.0-or-later"
21
22
 
22
23
  [project.urls]
23
24
  "Homepage" = "https://github.com/yufei-pan/Tee_Logger"
@@ -23,6 +23,7 @@ See Also:
23
23
  README.md for installation, log layout, and maintenance policy.
24
24
  """
25
25
  import datetime
26
+ import errno
26
27
  import os
27
28
  import logging
28
29
  import inspect
@@ -41,7 +42,7 @@ import threading
41
42
  import time
42
43
  import weakref
43
44
 
44
- version = '6.44'
45
+ version = '6.45'
45
46
  __version__ = version
46
47
 
47
48
  __author__ = 'Yufei Pan (pan@zopyr.us)'
@@ -438,6 +439,47 @@ def _tar_with_tarfile(folder, day, tmpArchive, disable_colors=...):
438
439
  _report(f'Failed to compress folder {day} due to {e}', 'error', disable_colors)
439
440
  return False
440
441
 
442
+ # fsync errors that mean the file system cannot sync (some FUSE and network file systems), not that a sync failed
443
+ _FSYNC_UNSUPPORTED = frozenset([errno.EINVAL, errno.ENOSYS]
444
+ + [getattr(errno, name) for name in ('ENOTSUP', 'EOPNOTSUPP') if hasattr(errno, name)])
445
+
446
+ def _fsync_path(path):
447
+ """Flush a file's data, or a directory's entries, to disk; raises OSError when the disk refuses.
448
+
449
+ Where the platform or file system cannot sync it (a directory on Windows, ``_FSYNC_UNSUPPORTED``),
450
+ this does nothing, as before 6.45: compressing must still work there.
451
+ """
452
+ isDir = os.path.isdir(path)
453
+ if isDir and os.name == 'nt':
454
+ return
455
+ # a file is opened read-write only because Windows cannot flush a read-only handle
456
+ flags = (os.O_RDONLY if isDir else os.O_RDWR) | getattr(os, 'O_BINARY', 0)
457
+ try:
458
+ fd = os.open(path, flags)
459
+ except OSError as e:
460
+ if isDir and e.errno in (errno.EACCES, errno.EPERM):
461
+ return # a mode 0300 directory we can write to but not open; any other error is real
462
+ raise
463
+ try:
464
+ os.fsync(fd)
465
+ except OSError as e:
466
+ if e.errno not in _FSYNC_UNSUPPORTED:
467
+ raise
468
+ finally:
469
+ os.close(fd)
470
+
471
+ def _sync_tmp_archive(tmpArchive, day, disable_colors=...):
472
+ """Flush the finished temporary archive to disk; on failure report it and return False.
473
+
474
+ The caller then puts the folder back and removes the claim, and the temporary archive with it.
475
+ """
476
+ try:
477
+ _fsync_path(tmpArchive)
478
+ return True
479
+ except OSError as e:
480
+ _report(f'Failed to sync the archive of {day} to disk due to {e}', 'error', disable_colors)
481
+ return False
482
+
441
483
  def compress_folder(folderPath, disable_colors=...):
442
484
  """Archive a log day-folder to ``YYYY-MM-DD.tar.xz`` next to it and remove the folder.
443
485
 
@@ -448,6 +490,13 @@ def compress_folder(folderPath, disable_colors=...):
448
490
  ``YYYY-MM-DD.deleting-<pid>`` rename). If anything fails, the folder is moved
449
491
  back. ``folderPath`` may also be a claim a crashed process left behind.
450
492
 
493
+ The logs are removed only after the archive's data and its name are on disk: the
494
+ temporary archive is fsynced before it is renamed into place, and the directory
495
+ is fsynced after. A rename does not flush the file's data, so without that a
496
+ crash soon after could leave an empty archive and no logs. If the directory sync
497
+ fails, the claim is left as it is; a stale claim is taken over by a later
498
+ cleanup, which archives the folder again.
499
+
451
500
  Uses ``tar`` and ``xz`` when available on the PATH; otherwise falls back to
452
501
  Python's ``tarfile`` module.
453
502
 
@@ -479,13 +528,15 @@ def compress_folder(folderPath, disable_colors=...):
479
528
  tmpArchive = os.path.join(claim, day + '.tar.xz.tmp')
480
529
  try:
481
530
  if os.path.isdir(claimedFolder):
482
- if not (_tar_with_cli(claim, day, tmpArchive, disable_colors)
483
- or _tar_with_tarfile(claimedFolder, day, tmpArchive, disable_colors)):
531
+ if not ((_tar_with_cli(claim, day, tmpArchive, disable_colors)
532
+ or _tar_with_tarfile(claimedFolder, day, tmpArchive, disable_colors))
533
+ and _sync_tmp_archive(tmpArchive, day, disable_colors)):
484
534
  # put the folder back so a later run can retry
485
535
  os.rename(claimedFolder, os.path.join(parent, day))
486
536
  shutil.rmtree(claim, ignore_errors=True)
487
537
  return False
488
538
  os.replace(tmpArchive, archive)
539
+ _fsync_path(parent) # an OSError here leaves the claim, with the logs in it
489
540
  elif not os.path.exists(archive):
490
541
  shutil.rmtree(claim, ignore_errors=True)
491
542
  return False
@@ -1,3 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: tee-logger
3
+ Version: 6.45
4
+ Summary: A simple wrapper for python logger that also selectively tee logs to stdout
5
+ Author-email: Yufei Pan <pan@zopyr.us>
6
+ License-Expression: GPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/yufei-pan/Tee_Logger
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.6
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=7.0; extra == "dev"
15
+ Dynamic: license-file
16
+
1
17
  # Tee_Logger
2
18
 
3
19
  A Python logger that writes to a dated log file and optionally mirrors output to stdout with ANSI colors. Supports in-place compression, automatic log archival, and smart caller line attribution.
@@ -135,7 +151,7 @@ On initialization and at each midnight rollover, `{programName}_log/` is scanned
135
151
 
136
152
  Folders with a file modified in the last 24 hours are left alone, in case another process is still writing there. A folder named like a date that is not one (`2020-13-45`) is skipped, with a message on stderr. The work runs in a background thread; the program exits only after an archive in progress is finished. `cleanup_old_logs()` runs the same maintenance synchronously.
137
153
 
138
- Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file and renamed into place, and only then is the folder deleted. If archiving fails, the folder is put back; a claim left by a crashed process is picked up again after 24 hours.
154
+ Compression uses system `tar`+`xz` when available, otherwise Python's `tarfile`. It is safe against crashes and concurrent cleanups: the folder is first renamed to `YYYY-MM-DD.compressing-<pid>/`, the archive is written to a temporary file, flushed to disk (fsync) and renamed into place, the directory is flushed too, and only then is the folder deleted. If archiving or the flush of the archive fails, the folder is put back; if the directory flush fails, the claim stays with the logs in it; a claim left by a crashed process is picked up again after 24 hours.
139
155
 
140
156
  ## API reference
141
157
 
@@ -177,6 +193,11 @@ python src/Tee_Logger.py -V
177
193
 
178
194
  CI runs on Python 3.9, 3.11, 3.12, and 3.14, plus 3.6 in a `python:3.6` container.
179
195
 
196
+ ## Upgrading to 6.45 from 6.44
197
+
198
+ - Packaging only: the license is declared as the SPDX expression `GPL-3.0-or-later` (no license classifier), so building from source needs setuptools 77.0.1 or later, which needs Python 3.9 or later. The code is unchanged. pip 9 (EL7, EL8) still installs the wheel; its `pip show` prints `License: None`, as it cannot read the new field.
199
+ - Compressing a day's logs flushes the archive to disk before it is renamed into place, and the log directory after, before the day's logs are deleted. Before, a crash or hard reset before the kernel wrote the archive back, often tens of seconds after a compression, could leave an empty or short `.tar.xz` and no logs (possible on XFS, and on ext4 for a new name). Where the file system cannot sync (some FUSE mounts), or the directory cannot be opened for it (a mode 0300 directory), or on Windows, the flush is skipped, as before. A disk that refuses the flush keeps the logs and reports `Failed to sync` or `Failed to compress folder` on stderr; a later cleanup tries again.
200
+
180
201
  ## Upgrading to 6.44 from 6.43
181
202
 
182
203
  - Compressed logs are written as one whole gzip member (xz or bz2 stream, zstd frame) per flush. In 6.43 a gzip or zstd log could not be read past the point where a run was killed, once a restarted run or a second process with the same `programName` appended to the same day's file; such a file now stays readable. The cost: gzip and zstd logs with frequent `WARNING`+ records, or with `flush_interval=0`, are larger (see the limitations above). xz and bz2 logs are unchanged.
@@ -1,5 +1,8 @@
1
1
  import datetime
2
+ import errno
2
3
  import os
4
+ import shutil
5
+ import stat
3
6
  import tarfile
4
7
  import threading
5
8
  import time
@@ -240,3 +243,154 @@ def test_cleanup_skips_recently_written_folder(tmp_path, setting):
240
243
  assert (logs_dir / "2020-06-01" / "sample_2020-06-01.log").read_text() == "still being written\n"
241
244
  assert not (logs_dir / "2020-06-01.tar.xz").exists()
242
245
  close_tee_logger(tl)
246
+
247
+
248
+ # --- the archive is on disk before the logs go (6.45) ---
249
+
250
+ @pytest.fixture
251
+ def record_compression():
252
+ """Start recording fsync, replace, the rename for deletion and rmtree, still running each for real.
253
+
254
+ ``start(parent, fsync_errors)`` returns the event list; ``parent`` is the folder holding the archive,
255
+ so a directory fsync is "fsync-dir" for it and "fsync-other-dir" for any other directory.
256
+ ``fsync_errors`` maps "file" or "dir" to an errno that kind of fsync raises instead. ``start.stop()``
257
+ undoes only these patches, so a ``tar_backend`` patch stays.
258
+ """
259
+ mp = pytest.MonkeyPatch()
260
+
261
+ def start(parent, fsync_errors=None):
262
+ events = []
263
+ real_fsync, real_replace, real_rename, real_rmtree = os.fsync, os.replace, os.rename, shutil.rmtree
264
+
265
+ def fsync(fd):
266
+ info = os.fstat(fd)
267
+ if not stat.S_ISDIR(info.st_mode):
268
+ kind = "file"
269
+ events.append("fsync-file")
270
+ else:
271
+ kind = "dir"
272
+ events.append("fsync-dir" if os.path.samestat(info, os.stat(str(parent))) else "fsync-other-dir")
273
+ if fsync_errors and kind in fsync_errors:
274
+ raise OSError(fsync_errors[kind], os.strerror(fsync_errors[kind]))
275
+ return real_fsync(fd)
276
+
277
+ def replace(src, dst):
278
+ events.append("replace")
279
+ return real_replace(src, dst)
280
+
281
+ def rename(src, dst):
282
+ if ".deleting-" in str(dst):
283
+ events.append("rename-to-deleting")
284
+ return real_rename(src, dst)
285
+
286
+ def rmtree(path, *args, **kwargs):
287
+ events.append("rmtree")
288
+ return real_rmtree(path, *args, **kwargs)
289
+
290
+ mp.setattr(Tee_Logger.os, "fsync", fsync)
291
+ mp.setattr(Tee_Logger.os, "replace", replace)
292
+ mp.setattr(Tee_Logger.os, "rename", rename)
293
+ mp.setattr(Tee_Logger.shutil, "rmtree", rmtree)
294
+ return events
295
+
296
+ start.stop = mp.undo
297
+ yield start
298
+ mp.undo()
299
+
300
+
301
+ @pytest.fixture(params=["tar-cli", "tarfile"])
302
+ def tar_backend(request, monkeypatch):
303
+ if request.param == "tarfile":
304
+ monkeypatch.setattr(Tee_Logger.shutil, "which", lambda name: None)
305
+ elif os.name == "nt" or not (shutil.which("tar") and shutil.which("xz")):
306
+ pytest.skip("no tar and xz on PATH")
307
+ return request.param
308
+
309
+
310
+ # Windows cannot open a directory to sync it, so there the directory fsync is skipped.
311
+ _DIR_SYNC = ["fsync-dir"] if os.name != "nt" else []
312
+ _ORDER = ["fsync-file", "replace"] + _DIR_SYNC + ["rename-to-deleting", "rmtree"]
313
+
314
+
315
+ def test_compress_folder_syncs_archive_before_replace_and_directory_before_removal(tmp_path, record_compression, tar_backend):
316
+ logs = tmp_path / "logs"
317
+ folder = _seed_day(logs, "2019-01-01", text="precious")
318
+ events = record_compression(logs)
319
+ assert compress_folder(str(folder), disable_colors=True) is True
320
+ # the directory synced is the one holding the archive, not the claim inside it
321
+ assert events[:len(_ORDER)] == _ORDER
322
+ assert events.count("fsync-file") == 1 and "fsync-other-dir" not in events
323
+ members = _archive_members(logs / "2019-01-01.tar.xz")
324
+ assert members["2019-01-01/sample_2019-01-01.log"] == b"precious\n"
325
+ assert sorted(p.name for p in logs.iterdir()) == ["2019-01-01.tar.xz"]
326
+
327
+
328
+ def test_compress_folder_archive_fsync_error_puts_the_folder_back(tmp_path, record_compression, tar_backend, capsys):
329
+ logs = tmp_path / "logs"
330
+ folder = _seed_day(logs, "2019-01-01", text="precious")
331
+ events = record_compression(logs, {"file": errno.EIO})
332
+ assert compress_folder(str(folder), disable_colors=True) is False
333
+ assert "replace" not in events and "rename-to-deleting" not in events
334
+ assert (folder / "sample_2019-01-01.log").read_text() == "precious\n"
335
+ assert sorted(p.name for p in logs.iterdir()) == ["2019-01-01"] # no archive, no claim, no temp file
336
+ assert "Failed to sync the archive" in capsys.readouterr().err
337
+
338
+
339
+ @pytest.mark.skipif(os.name == "nt", reason="Windows does not sync a directory")
340
+ def test_compress_folder_directory_fsync_error_keeps_the_logs_and_a_later_run_finishes(tmp_path, record_compression, tar_backend, capsys):
341
+ logs = tmp_path / "logs"
342
+ folder = _seed_day(logs, "2019-01-01", text="precious")
343
+ events = record_compression(logs, {"dir": errno.EIO})
344
+ assert compress_folder(str(folder), disable_colors=True) is False
345
+ assert "rename-to-deleting" not in events and "rmtree" not in events
346
+ claim = logs / f"2019-01-01.compressing-{os.getpid()}"
347
+ assert (claim / "2019-01-01" / "sample_2019-01-01.log").read_text() == "precious\n"
348
+ assert "Failed to compress folder" in capsys.readouterr().err
349
+ record_compression.stop() # the tar backend stays
350
+ # a later cleanup takes over the claim (what a stale one gets) and finishes
351
+ assert compress_folder(str(claim), disable_colors=True) is True
352
+ members = _archive_members(logs / "2019-01-01.tar.xz")
353
+ assert members["2019-01-01/sample_2019-01-01.log"] == b"precious\n"
354
+ assert sorted(p.name for p in logs.iterdir()) == ["2019-01-01.tar.xz"]
355
+
356
+
357
+ @pytest.mark.parametrize("code", [errno.EINVAL, errno.ENOSYS, getattr(errno, "ENOTSUP", errno.EINVAL)])
358
+ def test_compress_folder_carries_on_where_fsync_is_unsupported(tmp_path, record_compression, tar_backend, code):
359
+ logs = tmp_path / "logs"
360
+ folder = _seed_day(logs, "2019-01-01", text="precious")
361
+ events = record_compression(logs, {"file": code, "dir": code})
362
+ assert compress_folder(str(folder), disable_colors=True) is True
363
+ assert events[:len(_ORDER)] == _ORDER
364
+ assert sorted(p.name for p in logs.iterdir()) == ["2019-01-01.tar.xz"]
365
+
366
+
367
+ def _fail_opening(monkeypatch, logs, code):
368
+ real_open = os.open
369
+
370
+ def open_(path, flags, *args, **kwargs):
371
+ if os.fspath(path) == str(logs):
372
+ raise OSError(code, os.strerror(code))
373
+ return real_open(path, flags, *args, **kwargs)
374
+
375
+ monkeypatch.setattr(Tee_Logger.os, "open", open_)
376
+
377
+
378
+ @pytest.mark.parametrize("code", [errno.EACCES, errno.EPERM])
379
+ def test_compress_folder_carries_on_where_a_directory_cannot_be_opened(tmp_path, monkeypatch, tar_backend, code):
380
+ logs = tmp_path / "logs"
381
+ folder = _seed_day(logs, "2019-01-01", text="precious")
382
+ _fail_opening(monkeypatch, logs, code) # a mode 0300 directory, or Windows
383
+ assert compress_folder(str(folder), disable_colors=True) is True
384
+ assert sorted(p.name for p in logs.iterdir()) == ["2019-01-01.tar.xz"]
385
+
386
+
387
+ @pytest.mark.skipif(os.name == "nt", reason="Windows does not open a directory to sync it")
388
+ @pytest.mark.parametrize("code", [errno.EMFILE, errno.ENFILE, errno.EIO, errno.ENOMEM])
389
+ def test_compress_folder_keeps_the_logs_when_a_directory_open_fails_for_real(tmp_path, monkeypatch, tar_backend, code, capsys):
390
+ logs = tmp_path / "logs"
391
+ folder = _seed_day(logs, "2019-01-01", text="precious")
392
+ _fail_opening(monkeypatch, logs, code)
393
+ assert compress_folder(str(folder), disable_colors=True) is False
394
+ claim = logs / f"2019-01-01.compressing-{os.getpid()}"
395
+ assert (claim / "2019-01-01" / "sample_2019-01-01.log").read_text() == "precious\n"
396
+ assert "Failed to compress folder" in capsys.readouterr().err
File without changes
File without changes
File without changes