"""worker_logging 公共文件日志模块测试。 用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、 按大小轮转滚动备份、shutdown 恢复标准流。 依赖:标准库 + scripts/freight_rpa/common/worker_logging。 逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。 """ from __future__ import annotations import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common")) from worker_logging import ( # noqa: E402 WorkerLogTee, configure_file_logging, log_line_timestamp, rotate_log_file_if_needed, shutdown_logging, ) @pytest.fixture(autouse=True) def _restore_streams(): """每用例后强制恢复标准流并关闭日志,避免污染其他测试。""" yield shutdown_logging() def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys): """tee 应把带时间戳的行同时写入控制台与日志文件。""" log_file = (tmp_path / "worker.log").open("w", encoding="utf-8", buffering=1) tee = WorkerLogTee(sys.stdout, log_file) original_stdout = sys.stdout sys.stdout = tee try: print("hello-worker") finally: sys.stdout = original_stdout log_file.close() content = (tmp_path / "worker.log").read_text(encoding="utf-8") assert "hello-worker" in content assert content.startswith(log_line_timestamp()[:10]) # 日期前缀存在 assert "hello-worker" in capsys.readouterr().out def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch): """超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。""" monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "10") monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2") path = tmp_path / "worker.log" for round_no in range(3): path.write_text(f"round-{round_no}-padding", encoding="utf-8") rotate_log_file_if_needed(path) # [断言意图] 滚动语义:最新内容滚入 .1,次新在 .2,最旧(round-0)被删,主文件位空缺待新写入 assert Path(f"{path}.1").read_text(encoding="utf-8") == "round-2-padding" assert Path(f"{path}.2").read_text(encoding="utf-8") == "round-1-padding" assert not Path(f"{path}.3").exists() assert not path.exists() # 轮转后主文件位腾空,由调用方以追加模式重建 def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys): """configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。""" monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log")) enabled = configure_file_logging() assert enabled == tmp_path / "logs" / "worker.log" assert enabled.parent.is_dir() # 日志目录自动创建 print("banner-line") shutdown_logging() content = (tmp_path / "logs" / "worker.log").read_text(encoding="utf-8") assert "banner-line" in content assert "[logging] tee enabled" in content out = capsys.readouterr().out assert "banner-line" in out def test_configure_without_env_is_noop(monkeypatch): """未配置 LOG_FILE 时 configure 返回 None 且不改标准流。""" monkeypatch.delenv("FREIGHT_RPA_WORKER_LOG_FILE", raising=False) assert configure_file_logging() is None