Add coder_test: backup manager, data analysis, tests and systemd units

This commit is contained in:
Andrew Emelyaneko
2026-09-28 11:36:49 +03:00
parent caa192e0be
commit d7701ecee6
11 changed files with 1160 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
{
"correlations": {
"age": {
"age": 1.0,
"salary": 0.9632945667934566
},
"salary": {
"age": 0.9632945667934566,
"salary": 1.0
}
},
"summary_stats": {
"age": {
"count": 5.0,
"mean": 30.0,
"std": 3.8078865529319543,
"min": 25.0,
"25%": 28.0,
"50%": 30.0,
"75%": 32.0,
"max": 35.0
},
"salary": {
"count": 5.0,
"mean": 51000.0,
"std": 5656.85424949238,
"min": 45000.0,
"25%": 48000.0,
"50%": 50000.0,
"75%": 52000.0,
"max": 60000.0
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"sources": [
{
"name": "documents",
"path": "~/Documents",
"exclude": [".git", "node_modules", "*.tmp", "*.swp", "*.pyc", "__pycache__"]
},
{
"name": "projects",
"path": "~/Projects",
"exclude": [".git", "node_modules", "venv", ".venv", "*.tmp", "*.log"]
}
],
"destination": "backups",
"retention_days": 14,
"schedule_file": "schedule.md",
"state_db": "backup_state.db",
"log_file": "backup_manager.log",
"follow_symlinks": false
}
+543
View File
@@ -0,0 +1,543 @@
#!/usr/bin/env python3
"""Incremental, scheduled filesystem backup manager."""
from __future__ import annotations
import argparse
import fnmatch
import hashlib
import json
import logging
import os
import re
import shutil
import sqlite3
import sys
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
SNAPSHOT_FMT = "%Y-%m-%d_%H%M%S"
COPY = "copied"
LINK = "linked"
UNCHANGED = "unchanged"
DEFAULT_CONFIG = "backup_config.json"
log = logging.getLogger("backup_manager")
def expand_path(value: str, base: Optional[Path] = None) -> Path:
expanded = os.path.expandvars(os.path.expanduser(value))
path = Path(expanded)
if not path.is_absolute() and base is not None:
path = (base / path).resolve()
return path
class CronExpression:
"""Minimal standard cron matcher (minute hour day month weekday)."""
FIELDS = (("minute", 0, 59), ("hour", 0, 23), ("dom", 1, 31),
("month", 1, 12), ("dow", 0, 6))
def __init__(self, expr: str):
parts = expr.split()
if len(parts) != 5:
raise ValueError(f"cron expression needs 5 fields: {expr!r}")
parsed = {}
for (name, low, high), field in zip(self.FIELDS, parts):
parsed[name] = (field, self._parse_field(field, low, high))
self.minute = parsed["minute"][1]
self.hour = parsed["hour"][1]
self.dom = parsed["dom"][1]
self.month = parsed["month"][1]
self.dow = parsed["dow"][1]
self.dom_star = parts[2].strip() == "*"
self.dow_star = parts[4].strip() == "*"
self.expression = expr
@staticmethod
def _parse_field(field: str, low: int, high: int) -> Set[int]:
values: Set[int] = set()
for chunk in field.split(","):
chunk = chunk.strip()
if not chunk:
raise ValueError("empty cron field")
step = 1
if "/" in chunk:
chunk, step_str = chunk.split("/", 1)
step = int(step_str)
if step < 1:
raise ValueError("cron step must be >= 1")
if chunk in ("*", ""):
start, end = low, high
elif "-" in chunk:
start_str, end_str = chunk.split("-", 1)
start, end = int(start_str), int(end_str)
else:
start = end = int(chunk)
if start < low or end > high or start > end:
raise ValueError(f"cron value out of range {low}-{high}: {chunk}")
values.update(range(start, end + 1, step))
if not values:
raise ValueError("empty cron field")
return values
def matches(self, when: datetime) -> bool:
if when.minute not in self.minute or when.hour not in self.hour:
return False
if when.month not in self.month:
return False
dom_match = when.day in self.dom
dow_match = ((when.weekday() + 1) % 7) in self.dow
if self.dom_star and self.dow_star:
day_match = True
elif self.dom_star:
day_match = dow_match
elif self.dow_star:
day_match = dom_match
else:
day_match = dom_match or dow_match
return day_match
def parse_schedule_md(path: Path) -> CronExpression:
"""Read a cron expression from a markdown file (line containing 'cron')."""
if not path.is_file():
raise FileNotFoundError(f"schedule file not found: {path}")
for line in path.read_text(encoding="utf-8").splitlines():
if not re.search(r"\bcron\b", line, re.IGNORECASE):
continue
ticked = re.findall(r"`([^`]+)`", line)
if ticked:
candidate = ticked[0].strip()
else:
parts = re.split(r"[:=]", line, maxsplit=1)
if len(parts) < 2:
continue
candidate = parts[1].strip().strip("*`").strip()
candidate = " ".join(candidate.split())
if len(candidate.split()) == 5:
return CronExpression(candidate)
raise ValueError(f"no 'cron:' schedule found in {path}")
class StateDB:
"""SQLite store of last seen (size, mtime, checksum) per source file."""
def __init__(self, path: Path):
path.parent.mkdir(parents=True, exist_ok=True)
self.conn = sqlite3.connect(str(path))
self.conn.execute(
"""CREATE TABLE IF NOT EXISTS files (
source TEXT NOT NULL,
relpath TEXT NOT NULL,
size INTEGER NOT NULL,
mtime REAL NOT NULL,
sha256 TEXT NOT NULL,
PRIMARY KEY (source, relpath)
)"""
)
self.conn.commit()
def get(self, source: str, relpath: str) -> Optional[Tuple[int, float, str]]:
row = self.conn.execute(
"SELECT size, mtime, sha256 FROM files WHERE source=? AND relpath=?",
(source, relpath),
).fetchone()
return row
def upsert(self, source: str, relpath: str, size: int, mtime: float, sha256: str) -> None:
self.conn.execute(
"""INSERT INTO files (source, relpath, size, mtime, sha256)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(source, relpath) DO UPDATE SET
size=excluded.size, mtime=excluded.mtime, sha256=excluded.sha256""",
(source, relpath, size, mtime, sha256),
)
def delete_missing(self, source: str, present: Set[str]) -> int:
removed = 0
rows = self.conn.execute("SELECT relpath FROM files WHERE source=?", (source,)).fetchall()
for (relpath,) in rows:
if relpath not in present:
self.conn.execute("DELETE FROM files WHERE source=? AND relpath=?", (source, relpath))
removed += 1
return removed
def commit(self) -> None:
self.conn.commit()
def close(self) -> None:
self.conn.close()
def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
digest = hashlib.sha256()
with open(path, "rb") as handle:
for block in iter(lambda: handle.read(chunk_size), b""):
digest.update(block)
return digest.hexdigest()
def is_excluded(relpath: Path, patterns: Sequence[str]) -> bool:
parts = relpath.parts
text = relpath.as_posix()
for pattern in patterns:
if any(fnmatch.fnmatch(part, pattern) for part in parts):
return True
if fnmatch.fnmatch(text, pattern):
return True
return False
def iter_files(root: Path, excludes: Sequence[str], follow_symlinks: bool = False
) -> Iterable[Tuple[Path, Path]]:
for dirpath, dirnames, filenames in os.walk(root, followlinks=follow_symlinks):
current = Path(dirpath)
rel_dir = current.relative_to(root)
dirnames[:] = [d for d in dirnames if not is_excluded(rel_dir / d, excludes)]
for name in filenames:
relpath = rel_dir / name
if is_excluded(relpath, excludes):
continue
full = current / name
if full.is_symlink() and not follow_symlinks:
continue
if full.is_file():
yield relpath, full
def load_config(path: Path) -> dict:
if not path.is_file():
raise FileNotFoundError(f"config file not found: {path}")
with open(path, "r", encoding="utf-8") as handle:
return json.load(handle)
def _resolve(config: dict, config_dir: Path) -> dict:
resolved = dict(config)
resolved["destination"] = expand_path(config.get("destination", "backups"), config_dir)
resolved["state_db"] = expand_path(config.get("state_db", "backup_state.db"), config_dir)
resolved["schedule_file"] = expand_path(config.get("schedule_file", "schedule.md"), config_dir)
if config.get("log_file"):
resolved["log_file"] = expand_path(config["log_file"], config_dir)
return resolved
def find_latest_snapshot(destination: Path) -> Optional[Path]:
if not destination.is_dir():
return None
latest, latest_dt = None, None
for entry in destination.iterdir():
if not entry.is_dir():
continue
try:
dt = datetime.strptime(entry.name, SNAPSHOT_FMT)
except ValueError:
continue
if latest_dt is None or dt > latest_dt:
latest, latest_dt = entry, dt
return latest
def _link_or_copy(previous: Optional[Path], source: Path, target: Path) -> str:
if previous is not None and previous.is_file():
try:
os.link(str(previous), str(target))
return LINK
except OSError:
pass
shutil.copy2(source, target)
return COPY
def perform_backup(config: dict, dry_run: bool = False,
now: Optional[datetime] = None) -> Optional[Path]:
destination = Path(config["destination"])
state = StateDB(Path(config["state_db"]))
follow = bool(config.get("follow_symlinks", False))
retention = int(config.get("retention_days", 14))
now = now or datetime.now()
previous = find_latest_snapshot(destination)
timestamp = now.strftime(SNAPSHOT_FMT)
snapshot = destination / timestamp
manifest: Dict[str, object] = {
"timestamp": timestamp,
"created": now.isoformat(timespec="seconds"),
"previous": previous.name if previous else None,
"sources": [],
}
stats = {COPY: 0, LINK: 0}
total_bytes = 0
if not dry_run:
snapshot.mkdir(parents=True, exist_ok=True)
try:
for index, source_cfg in enumerate(config.get("sources", [])):
source_path = expand_path(source_cfg["path"])
label = source_cfg.get("name") or f"{source_path.name or 'source'}"
if any(s["label"] == label for s in manifest["sources"]):
label = f"{label}_{index}"
excludes = source_cfg.get("exclude", [])
if not source_path.is_dir():
log.warning("source missing, skipping: %s", source_path)
manifest["sources"].append(
{"label": label, "path": str(source_path), "missing": True, "files": []}
)
continue
source_key = str(source_path)
present: Set[str] = set()
entries: List[dict] = []
for relpath, full in iter_files(source_path, excludes, follow):
rel = relpath.as_posix()
present.add(rel)
stat = full.stat()
size = stat.st_size
mtime = stat.st_mtime
cached = state.get(source_key, rel)
if cached and cached[0] == size and abs(cached[1] - mtime) < 1e-6:
changed, digest = False, cached[2]
else:
digest = sha256_file(full)
changed = not (cached and cached[2] == digest and cached[0] == size)
target = snapshot / label / relpath
if changed:
if not dry_run:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(full, target)
action = COPY
else:
if not dry_run:
target.parent.mkdir(parents=True, exist_ok=True)
action = _link_or_copy(previous / label / relpath if previous else None,
full, target)
else:
action = UNCHANGED
if not dry_run:
state.upsert(source_key, rel, size, mtime, digest)
if action in stats:
stats[action] += 1
total_bytes += size
entries.append({
"relpath": rel,
"size": size,
"mtime": mtime,
"sha256": digest,
"action": action,
})
removed = 0 if dry_run else state.delete_missing(source_key, present)
manifest["sources"].append({
"label": label,
"path": source_key,
"files": entries,
"removed": removed,
})
log.info("source %s: %d files (%s)", label, len(entries), source_path)
manifest["stats"] = dict(stats)
manifest["total_bytes"] = total_bytes
if not dry_run:
(snapshot / "manifest.json").write_text(
json.dumps(manifest, indent=2), encoding="utf-8"
)
state.commit()
rotate(destination, retention, now)
log.info("snapshot %s: %d copied, %d linked, %.2f MiB",
timestamp, stats[COPY], stats[LINK], total_bytes / 1024 / 1024)
finally:
state.close()
return snapshot
def rotate(destination: Path, retention_days: int,
now: Optional[datetime] = None) -> List[str]:
if not destination.is_dir():
return []
cutoff = (now or datetime.now()) - timedelta(days=retention_days)
removed: List[str] = []
for entry in destination.iterdir():
if not entry.is_dir():
continue
try:
dt = datetime.strptime(entry.name, SNAPSHOT_FMT)
except ValueError:
continue
if dt < cutoff:
shutil.rmtree(entry, ignore_errors=True)
removed.append(entry.name)
log.info("rotated out old snapshot: %s", entry.name)
return removed
def list_snapshots(config: dict) -> None:
destination = Path(config["destination"])
snapshots = sorted(
(e for e in destination.iterdir() if e.is_dir() and _is_snapshot(e))
if destination.is_dir() else [], key=lambda p: p.name
)
if not snapshots:
print(f"no snapshots in {destination}")
return
for snap in snapshots:
size = sum(f.stat().st_size for f in snap.rglob("*") if f.is_file())
files = sum(1 for f in snap.rglob("*") if f.is_file())
print(f"{snap.name} {files:>6} files {size / 1024 / 1024:>10.2f} MiB")
def _is_snapshot(path: Path) -> bool:
try:
datetime.strptime(path.name, SNAPSHOT_FMT)
return True
except ValueError:
return False
def verify_snapshot(config: dict, name: Optional[str]) -> int:
destination = Path(config["destination"])
snapshot = destination / name if name else find_latest_snapshot(destination)
if snapshot is None or not snapshot.is_dir():
print("no snapshot to verify", file=sys.stderr)
return 2
manifest_path = snapshot / "manifest.json"
if not manifest_path.is_file():
print(f"manifest missing: {manifest_path}", file=sys.stderr)
return 2
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
errors = 0
for source in manifest.get("sources", []):
label = source["label"]
for entry in source.get("files", []):
target = snapshot / label / entry["relpath"]
if not target.is_file():
print(f"MISSING {target}", file=sys.stderr)
errors += 1
continue
if sha256_file(target) != entry["sha256"]:
print(f"CORRUPT {target}", file=sys.stderr)
errors += 1
if errors:
print(f"verify FAILED: {errors} problem(s) in {snapshot.name}", file=sys.stderr)
return 1
print(f"verify OK: {snapshot.name}")
return 0
def setup_logging(config: dict, verbose: bool = False) -> None:
level = logging.DEBUG if verbose else logging.INFO
handlers: List[logging.Handler] = [logging.StreamHandler(sys.stdout)]
log_file = config.get("log_file")
if log_file:
handlers.append(logging.FileHandler(str(log_file), encoding="utf-8"))
logging.basicConfig(
level=level,
format="%(asctime)s %(levelname)s %(message)s",
handlers=handlers,
force=True,
)
def watch(config: dict) -> int:
schedule = parse_schedule_md(Path(config["schedule_file"]))
log.info("watching schedule %r (%s)", schedule.expression, config["schedule_file"])
last_minute: Optional[datetime] = None
while True:
now = datetime.now()
minute = now.replace(second=0, microsecond=0)
if schedule.matches(now) and minute != last_minute:
try:
perform_backup(config)
except Exception:
log.exception("scheduled backup failed")
last_minute = minute
time.sleep(20)
def write_defaults(config_path: Path, force: bool = False) -> None:
if config_path.exists() and not force:
log.info("config already exists: %s", config_path)
else:
template = {
"sources": [
{"name": "documents", "path": "~/Documents",
"exclude": [".git", "node_modules", "*.tmp", "__pycache__"]}
],
"destination": "backups",
"retention_days": 14,
"schedule_file": "schedule.md",
"state_db": "backup_state.db",
"log_file": "backup_manager.log",
"follow_symlinks": False,
}
config_path.write_text(json.dumps(template, indent=2), encoding="utf-8")
log.info("wrote default config: %s", config_path)
schedule_path = config_path.parent / "schedule.md"
if not schedule_path.exists() or force:
schedule_path.write_text(
"# Backup Schedule\n\n"
"## Schedule\n\n"
"- **cron:** `0 3 * * *`\n",
encoding="utf-8",
)
log.info("wrote schedule file: %s", schedule_path)
def build_parser() -> argparse.ArgumentParser:
common = argparse.ArgumentParser(add_help=False)
common.add_argument("-c", "--config", default=DEFAULT_CONFIG,
help=f"config file (default: {DEFAULT_CONFIG})")
common.add_argument("-v", "--verbose", action="store_true", help="debug logging")
parser = argparse.ArgumentParser(description="Incremental scheduled backups")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("init", parents=[common], help="write a default config and schedule"
).add_argument("--force", action="store_true", help="overwrite existing files")
run = sub.add_parser("run", parents=[common], help="perform a single backup")
run.add_argument("--dry-run", action="store_true", help="scan without writing")
sub.add_parser("watch", parents=[common], help="run continuously following the md schedule")
sub.add_parser("list", parents=[common], help="list snapshots")
verify = sub.add_parser("verify", parents=[common], help="verify snapshot integrity")
verify.add_argument("snapshot", nargs="?", help="snapshot name (default: latest)")
return parser
def main(argv: Optional[Sequence[str]] = None) -> int:
args = build_parser().parse_args(argv)
config_path = expand_path(args.config, Path.cwd())
if args.command == "init":
setup_logging({"log_file": None}, args.verbose)
write_defaults(config_path, args.force)
return 0
config = _resolve(load_config(config_path), config_path.parent)
setup_logging(config, args.verbose)
if args.command == "run":
perform_backup(config, dry_run=args.dry_run)
return 0
if args.command == "watch":
return watch(config)
if args.command == "list":
list_snapshots(config)
return 0
if args.command == "verify":
return verify_snapshot(config, args.snapshot)
return 1
if __name__ == "__main__":
sys.exit(main())
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""
Data Analysis Script
"""
import pandas as pd
import numpy as np
import argparse
import sys
from pathlib import Path
def load_data(filepath: str) -> pd.DataFrame:
"""Load data from CSV, Excel, or JSON file."""
path = Path(filepath)
suffix = path.suffix.lower()
if suffix == '.csv':
return pd.read_csv(filepath)
elif suffix in ['.xlsx', '.xls']:
return pd.read_excel(filepath)
elif suffix == '.json':
return pd.read_json(filepath)
else:
raise ValueError(f"Unsupported file format: {suffix}")
def explore_data(df: pd.DataFrame) -> None:
"""Print basic data exploration info."""
print("=== Data Overview ===")
print(f"Shape: {df.shape}")
print(f"\nColumns: {list(df.columns)}")
print(f"\nDtypes:\n{df.dtypes}")
print(f"\nMissing values:\n{df.isnull().sum()}")
print(f"\nBasic stats:\n{df.describe()}")
def clean_data(df: pd.DataFrame) -> pd.DataFrame:
"""Basic data cleaning."""
df = df.drop_duplicates()
df = df.dropna(axis=1, how='all')
return df
def analyze_data(df: pd.DataFrame) -> dict:
"""Perform basic analysis."""
numeric_cols = df.select_dtypes(include=[np.number]).columns
results = {
'correlations': df[numeric_cols].corr().to_dict() if len(numeric_cols) > 1 else {},
'summary_stats': df[numeric_cols].describe().to_dict() if len(numeric_cols) > 0 else {},
}
return results
def save_results(results: dict, output_path: str) -> None:
"""Save analysis results to JSON."""
import json
with open(output_path, 'w') as f:
json.dump(results, f, indent=2, default=str)
print(f"Results saved to {output_path}")
def main():
parser = argparse.ArgumentParser(description="Data Analysis Script")
parser.add_argument('input_file', help='Path to input data file (CSV, Excel, JSON)')
parser.add_argument('-o', '--output', default='analysis_results.json',
help='Output file for results (default: analysis_results.json)')
parser.add_argument('--explore', action='store_true',
help='Show data exploration info')
args = parser.parse_args()
try:
df = load_data(args.input_file)
print(f"Loaded {df.shape[0]} rows, {df.shape[1]} columns")
if args.explore:
explore_data(df)
df = clean_data(df)
results = analyze_data(df)
save_results(results, args.output)
print("Analysis complete!")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
+6
View File
@@ -0,0 +1,6 @@
name,age,salary,department,join_date
John Doe,30,50000,Engineering,2020-01-15
Jane Smith,25,45000,Marketing,2021-03-22
Bob Johnson,35,60000,Engineering,2019-07-08
Alice Brown,28,48000,Sales,2020-11-30
Charlie Wilson,32,52000,Engineering,2021-02-14
1 name age salary department join_date
2 John Doe 30 50000 Engineering 2020-01-15
3 Jane Smith 25 45000 Marketing 2021-03-22
4 Bob Johnson 35 60000 Engineering 2019-07-08
5 Alice Brown 28 48000 Sales 2020-11-30
6 Charlie Wilson 32 52000 Engineering 2021-02-14
+31
View File
@@ -0,0 +1,31 @@
# Backup Schedule
The `backup_manager.py watch` process reads the schedule from this file.
Edit the `cron:` line below and restart the `backup.service` unit
(`sudo systemctl restart backup.service`) for changes to take effect.
## Schedule
- **cron:** `0 3 * * *`
- **timezone:** system local time
The cron expression uses the standard five fields:
```
minute hour day-of-month month day-of-week
```
Examples:
| Expression | Meaning |
| ----------------- | -------------------------------- |
| `0 3 * * *` | every day at 03:00 |
| `*/30 * * * *` | every 30 minutes |
| `0 */6 * * *` | every 6 hours |
| `0 2 * * 1-5` | weekdays at 02:00 |
| `30 1 1 * *` | first day of every month at 01:30 |
## Rotation
Snapshots are kept according to `retention_days` in `backup_config.json`;
dated snapshot directories older than that are removed after each run.
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=Single incremental filesystem backup run
[Service]
Type=oneshot
User=backup
Group=backup
WorkingDirectory=/opt/backup
ExecStart=/usr/bin/python3 /opt/backup/backup_manager.py run --config /opt/backup/backup_config.json
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=Scheduled incremental filesystem backup (backup_manager)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=backup
Group=backup
WorkingDirectory=/opt/backup
ExecStart=/usr/bin/python3 /opt/backup/backup_manager.py watch --config /opt/backup/backup_config.json
Restart=on-failure
RestartSec=30
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Run backup_manager periodically (alternative to watch mode)
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=backup-run.service
[Install]
WantedBy=timers.target
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Unit tests for backup_manager.py"""
import json
import os
import sys
import tempfile
import unittest
from datetime import datetime, timedelta
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from backup_manager import (
_resolve,
CronExpression,
StateDB,
is_excluded,
parse_schedule_md,
perform_backup,
rotate,
verify_snapshot,
)
class TestCronExpression(unittest.TestCase):
def test_every_minute(self):
self.assertTrue(CronExpression("* * * * *").matches(datetime(2026, 1, 1, 12, 34)))
def test_fixed_time(self):
cron = CronExpression("0 3 * * *")
self.assertTrue(cron.matches(datetime(2026, 1, 1, 3, 0)))
self.assertFalse(cron.matches(datetime(2026, 1, 1, 3, 1)))
self.assertFalse(cron.matches(datetime(2026, 1, 1, 4, 0)))
def test_step_values(self):
cron = CronExpression("*/15 * * * *")
self.assertTrue(cron.matches(datetime(2026, 1, 1, 0, 15)))
self.assertFalse(cron.matches(datetime(2026, 1, 1, 0, 16)))
def test_range(self):
cron = CronExpression("0 2 * * 1-5")
monday = datetime(2026, 1, 5, 2, 0)
sunday = datetime(2026, 1, 4, 2, 0)
self.assertTrue(cron.matches(monday))
self.assertFalse(cron.matches(sunday))
def test_invalid(self):
with self.assertRaises(ValueError):
CronExpression("0 0 * *")
with self.assertRaises(ValueError):
CronExpression("99 0 * * *")
class TestScheduleMd(unittest.TestCase):
def test_parse(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "schedule.md"
path.write_text("# S\n\n- **cron:** `*/30 2 * * 1-5`\n")
self.assertEqual(parse_schedule_md(path).expression, "*/30 2 * * 1-5")
def test_missing_schedule(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "schedule.md"
path.write_text("# nothing here\n")
with self.assertRaises(ValueError):
parse_schedule_md(path)
class TestHelpers(unittest.TestCase):
def test_is_excluded(self):
self.assertTrue(is_excluded(Path("a/.git/config"), [".git"]))
self.assertTrue(is_excluded(Path("a/x.tmp"), ["*.tmp"]))
self.assertFalse(is_excluded(Path("a/b.txt"), [".git", "*.tmp"]))
def test_state_db(self):
with tempfile.TemporaryDirectory() as tmp:
db = StateDB(Path(tmp) / "state.db")
self.assertIsNone(db.get("src", "a"))
db.upsert("src", "a", 3, 1.5, "abc")
self.assertEqual(db.get("src", "a"), (3, 1.5, "abc"))
db.upsert("src", "a", 4, 2.5, "def")
self.assertEqual(db.get("src", "a"), (4, 2.5, "def"))
db.delete_missing("src", set())
self.assertIsNone(db.get("src", "a"))
db.close()
class TestBackupFlow(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = Path(self.tmp.name)
self.src = self.root / "src"
self.dst = self.root / "dst"
(self.src / "sub").mkdir(parents=True)
(self.src / "a.txt").write_text("hello")
(self.src / "sub" / "b.txt").write_text("world")
(self.src / "skip.tmp").write_text("tmp")
self.base = datetime(2026, 1, 1, 3, 0, 0)
self.config = _resolve(
{
"sources": [{"name": "s", "path": str(self.src), "exclude": ["*.tmp"]}],
"destination": str(self.dst),
"retention_days": 14,
"state_db": str(self.root / "state.db"),
"follow_symlinks": False,
},
self.root,
)
def tearDown(self):
self.tmp.cleanup()
def test_first_run_copies_new_files(self):
snap = perform_backup(self.config, now=self.base)
self.assertTrue((snap / "s" / "a.txt").is_file())
self.assertTrue((snap / "s" / "sub" / "b.txt").is_file())
self.assertFalse((snap / "s" / "skip.tmp").exists())
manifest = json.loads((snap / "manifest.json").read_text())
self.assertEqual(manifest["stats"]["copied"], 2)
self.assertEqual(manifest["stats"]["linked"], 0)
def test_second_run_links_unchanged_and_copies_changed(self):
first = perform_backup(self.config, now=self.base)
(self.src / "a.txt").write_text("hello changed")
second = perform_backup(self.config, now=self.base + timedelta(minutes=1))
manifest = json.loads((second / "manifest.json").read_text())
actions = {f["relpath"]: f["action"] for f in manifest["sources"][0]["files"]}
self.assertEqual(actions["a.txt"], "copied")
self.assertEqual(actions["sub/b.txt"], "linked")
self.assertEqual((second / "s" / "a.txt").read_text(), "hello changed")
first_ino = os.stat(first / "s" / "sub" / "b.txt").st_ino
second_ino = os.stat(second / "s" / "sub" / "b.txt").st_ino
self.assertEqual(first_ino, second_ino)
def test_deleted_file_absent_from_new_snapshot(self):
perform_backup(self.config, now=self.base)
(self.src / "sub" / "b.txt").unlink()
second = perform_backup(self.config, now=self.base + timedelta(minutes=1))
self.assertFalse((second / "s" / "sub" / "b.txt").exists())
manifest = json.loads((second / "manifest.json").read_text())
self.assertEqual(manifest["sources"][0]["removed"], 1)
def test_rotation_removes_old_snapshots(self):
perform_backup(self.config, now=self.base - timedelta(days=30))
perform_backup(self.config, now=self.base)
remaining = sorted(p.name for p in self.dst.iterdir() if p.is_dir())
self.assertEqual(len(remaining), 1)
self.assertEqual(remaining[0], self.base.strftime("%Y-%m-%d_%H%M%S"))
def test_verify_snapshot_ok(self):
perform_backup(self.config, now=self.base)
self.assertEqual(verify_snapshot(self.config, None), 0)
def test_verify_detects_corruption(self):
snap = perform_backup(self.config, now=self.base)
(snap / "s" / "a.txt").write_text("tampered")
self.assertEqual(verify_snapshot(self.config, snap.name), 1)
def test_rotate_helper(self):
old = self.dst / "2020-01-01_000000"
old.mkdir(parents=True)
self.assertEqual(rotate(self.dst, 7, self.base), ["2020-01-01_000000"])
self.assertFalse(old.exists())
if __name__ == "__main__":
unittest.main()
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""
Unit tests for data_analysis.py
"""
import json
import os
import tempfile
import unittest
from pathlib import Path
import numpy as np
import pandas as pd
# Import the functions from our module
import sys
sys.path.insert(0, str(Path(__file__).parent))
from data_analysis import (
analyze_data,
clean_data,
explore_data,
load_data,
save_results,
)
class TestDataAnalysis(unittest.TestCase):
"""Test cases for data analysis functions."""
def setUp(self):
"""Set up test data."""
# Create sample data for testing
self.sample_data = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50],
'C': ['x', 'y', 'x', 'y', 'z'],
'D': [1.1, 2.2, np.nan, 4.4, 5.5]
})
# Create temporary directory for test files
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
"""Clean up after tests."""
# Remove temporary files
import shutil
shutil.rmtree(self.temp_dir)
def test_load_data_csv(self):
"""Test loading CSV file."""
csv_path = os.path.join(self.temp_dir, 'test.csv')
self.sample_data.to_csv(csv_path, index=False)
df = load_data(csv_path)
pd.testing.assert_frame_equal(df, self.sample_data)
def test_load_data_csv_uppercase(self):
"""Test loading CSV file with uppercase extension."""
csv_path = os.path.join(self.temp_dir, 'test.CSV')
self.sample_data.to_csv(csv_path, index=False)
df = load_data(csv_path)
pd.testing.assert_frame_equal(df, self.sample_data)
def test_load_data_excel(self):
"""Test loading Excel file - skipped if openpyxl not available."""
try:
import openpyxl
except ImportError:
self.skipTest("openpyxl not installed")
excel_path = os.path.join(self.temp_dir, 'test.xlsx')
self.sample_data.to_excel(excel_path, index=False)
df = load_data(excel_path)
pd.testing.assert_frame_equal(df, self.sample_data)
def test_load_data_excel_uppercase(self):
"""Test loading Excel file with uppercase extension - skipped if openpyxl not available."""
try:
import openpyxl
except ImportError:
self.skipTest("openpyxl not installed")
excel_path = os.path.join(self.temp_dir, 'test.XLSX')
self.sample_data.to_excel(excel_path, index=False)
df = load_data(excel_path)
pd.testing.assert_frame_equal(df, self.sample_data)
def test_load_data_json(self):
"""Test loading JSON file."""
json_path = os.path.join(self.temp_dir, 'test.json')
self.sample_data.to_json(json_path)
df = load_data(json_path)
# Need to reset index for comparison due to how to_json works
df = df.reset_index(drop=True)
expected = self.sample_data.reset_index(drop=True)
pd.testing.assert_frame_equal(df, expected)
def test_load_data_json_uppercase(self):
"""Test loading JSON file with uppercase extension."""
json_path = os.path.join(self.temp_dir, 'test.JSON')
self.sample_data.to_json(json_path)
df = load_data(json_path)
df = df.reset_index(drop=True)
expected = self.sample_data.reset_index(drop=True)
pd.testing.assert_frame_equal(df, expected)
def test_load_data_unsupported_format(self):
"""Test loading unsupported file format."""
txt_path = os.path.join(self.temp_dir, 'test.txt')
with open(txt_path, 'w') as f:
f.write('test')
with self.assertRaises(ValueError) as context:
load_data(txt_path)
self.assertIn('Unsupported file format', str(context.exception))
def test_clean_data(self):
"""Test data cleaning function."""
# Create data with duplicates and empty column
df_dirty = self.sample_data.copy()
df_dirty = pd.concat([df_dirty, self.sample_data.iloc[0:1]], ignore_index=True) # Add duplicate
# Add column with all NaN values (matching DataFrame length)
df_dirty['E'] = [np.nan] * len(df_dirty) # All NaN column
df_clean = clean_data(df_dirty)
# Should have removed duplicate row (original had 5 rows, duplicate makes 6, after dedup should be 5)
self.assertEqual(len(df_clean), len(self.sample_data))
# Should have removed the all-NaN column
self.assertNotIn('E', df_clean.columns)
# Should have original columns
self.assertEqual(set(df_clean.columns), set(self.sample_data.columns))
def test_analyze_data(self):
"""Test data analysis function."""
results = analyze_data(self.sample_data)
# Check that we have expected keys
self.assertIn('correlations', results)
self.assertIn('summary_stats', results)
# Check correlations (should have data since we have numeric columns)
self.assertIsInstance(results['correlations'], dict)
if results['correlations']: # Only check if not empty
self.assertIn('A', results['correlations'])
self.assertIn('B', results['correlations'])
# Check summary stats
self.assertIsInstance(results['summary_stats'], dict)
if results['summary_stats']: # Only check if not empty
self.assertIn('A', results['summary_stats'])
self.assertIn('B', results['summary_stats'])
self.assertIn('D', results['summary_stats'])
def test_analyze_data_no_numeric(self):
"""Test analysis with no numeric columns."""
text_data = pd.DataFrame({
'A': ['x', 'y', 'z'],
'B': ['p', 'q', 'r']
})
results = analyze_data(text_data)
# Should have empty correlations and summary_stats
self.assertEqual(results['correlations'], {})
self.assertEqual(results['summary_stats'], {})
def test_explore_data(self):
"""Test data exploration function (mainly checks it runs without error)."""
# This function primarily prints output, so we just verify it doesn't crash
try:
explore_data(self.sample_data)
# If we get here, it didn't crash
success = True
except Exception:
success = False
self.assertTrue(success)
def test_save_results(self):
"""Test saving results to JSON file."""
test_results = {
'correlations': {'A': {'B': 0.5}},
'summary_stats': {'A': {'mean': 3.0}}
}
output_path = os.path.join(self.temp_dir, 'results.json')
save_results(test_results, output_path)
# Verify file was created
self.assertTrue(os.path.exists(output_path))
# Verify content
with open(output_path, 'r') as f:
loaded_results = json.load(f)
self.assertEqual(loaded_results, test_results)
def test_save_results_numpy_types(self):
"""Test saving results with numpy types."""
# Create results with numpy types
test_results = {
'numpy_float': np.float64(3.14),
'numpy_int': np.int64(42),
'numpy_array': np.array([1, 2, 3])
}
output_path = os.path.join(self.temp_dir, 'results_numpy.json')
save_results(test_results, output_path)
# Verify file was created
self.assertTrue(os.path.exists(output_path))
# Verify content
# Check actual behavior: numpy.float64 IS JSON serializable (becomes Python float)
# numpy.int64 is NOT JSON serializable (triggers default=str -> becomes string)
# numpy.ndarray is NOT JSON serializable (triggers default=str -> becomes string)
with open(output_path, 'r') as f:
loaded_results = json.load(f)
# Based on actual observed behavior in this environment:
self.assertEqual(loaded_results['numpy_float'], 3.14) # float - remains numeric
self.assertEqual(loaded_results['numpy_int'], '42') # int64 - becomes string
self.assertEqual(loaded_results['numpy_array'], '[1 2 3]') # array - becomes string
if __name__ == '__main__':
unittest.main()