Files
linux-backuper/tests/test_transport.py
T
soda64 4b3346fd74
Test, Lint and Security Gate / Security Scan and Quality Audits (push) Failing after 8s
Test, Lint and Security Gate / Unit & Security Tests (Coverage >= 80%) (push) Has been skipped
Build and Publish Release / Build Packages and Publish (push) Successful in 1m31s
feat: modernize to Software Factory standards, add AppSec suite, and bump to v2.0.0
- Refactor tests to achieve 100% Zero-Mocks compliance (remove unittest.mock, add tests.helpers.env_override and stdlib redirects)
- Extract testable parsing methods in package managers and inspector
- Add tests/test_security.py with 5 negative AppSec test cases (Zip Slip, Root Gate, Tampering SHA-256, Secret Sanitization, and AST check for zero shell=True)
- Expand is_sanitized_target to redact all private SSH/TLS keys (*.key, *.pem, id_*)
- Split Gitea CI/CD pipelines into test-and-lint.yaml and build-and-release.yaml
- Add .gitleaks.toml configuration
- Formally close v1.0.0 genesis plan in docs/plans/linux-backuper/00-status.md as immutable ADR
- Bump version to v2.0.0 across __init__.py, man page, tests, and documentation
2026-10-23 22:08:15 +02:00

164 lines
6.0 KiB
Python

"""Unit tests for RemoteTransport and push command."""
from contextlib import redirect_stdout
import io
import json
import os
import shutil
import tempfile
import unittest
from tests.helpers import env_override
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_GENERIC_ERROR
from linux_backuper.core.retention import RetentionEngine
from linux_backuper.core.transport import (
LocalPathTransport,
SshTransport,
TransportFactory,
TransportError
)
from linux_backuper.models import SnapshotManifest
class TestRemoteTransport(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_transport_")
self.backup_dir = os.path.join(self.test_dir, "local_backups")
self.remote_dir = os.path.join(self.test_dir, "remote_nas")
os.makedirs(self.backup_dir, exist_ok=True)
os.makedirs(self.remote_dir, exist_ok=True)
# Create a mock snapshot locally
self.archiver = SnapshotArchiver(target_dir=self.backup_dir)
dummy_f = os.path.join(self.test_dir, "sample.txt")
with open(dummy_f, "w") as f:
f.write("hello transport\n")
entries, sha, uncomp, _ = self.archiver.collect_file_list([dummy_f])
self.manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id="snap_transport_1",
created_at="2026-10-09T12:00:00Z",
hostname="host1",
profile="quick",
compression="gzip",
os={},
package_manager="none",
package_count=0,
included_paths=[dummy_f],
stats={"file_count": 1, "uncompressed_bytes": uncomp, "compressed_bytes": 0},
files_sha256=sha
)
self.archive_path = self.archiver.create_snapshot_archive("snap_transport_1", self.manifest, entries)
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_local_path_transport_push_and_verify(self):
transport = LocalPathTransport(self.remote_dir)
res = transport.push(self.archive_path)
self.assertEqual(res["status"], "success")
self.assertEqual(res["transport"], "local_mount")
dest_path = res["destination_path"]
self.assertTrue(os.path.isfile(dest_path))
self.assertEqual(os.path.basename(dest_path), os.path.basename(self.archive_path))
# Check strict permissions (0600)
mode = os.stat(dest_path).st_mode & 0o777
self.assertEqual(mode, 0o600)
def test_local_path_transport_remote_prune(self):
transport = LocalPathTransport(self.remote_dir)
# Push first archive
transport.push(self.archive_path)
# Create second archive and push
m2 = SnapshotManifest.from_dict(self.manifest.to_dict())
m2.snapshot_id = "snap_transport_2"
m2.created_at = "2026-10-09T14:00:00Z"
arc2 = self.archiver.create_snapshot_archive("snap_transport_2", m2, [(os.path.join(self.test_dir, "sample.txt"), "data/sample.txt")])
transport.push(arc2)
# 2 archives on remote
self.assertEqual(len(transport.list_remote()), 2)
# Prune remote with keep-last 1
retention = RetentionEngine(keep_last=1)
pruned_results = transport.prune_remote(retention)
self.assertEqual(len(pruned_results), 1)
self.assertEqual(pruned_results[0]["action"], "deleted")
self.assertEqual(len(transport.list_remote()), 1)
self.assertEqual(transport.list_remote()[0].snapshot_id, "snap_transport_2")
def test_transport_factory_parsing(self):
# Local dir
t1 = TransportFactory.get_transport("/mnt/nas/backups")
self.assertIsInstance(t1, LocalPathTransport)
# SSH
t2 = TransportFactory.get_transport("backupuser@nas.local:/volume1/backups")
self.assertIsInstance(t2, SshTransport)
self.assertEqual(t2.user, "backupuser")
self.assertEqual(t2.host, "nas.local")
self.assertEqual(t2.remote_dir, "/volume1/backups")
# Config alias
cfg = {
"remotes": {
"mynas": {
"type": "ssh",
"host": "192.168.1.100",
"user": "admin",
"path": "/backups"
}
}
}
t3 = TransportFactory.get_transport("mynas", config=cfg)
self.assertIsInstance(t3, SshTransport)
self.assertEqual(t3.host, "192.168.1.100")
def test_cli_push_command(self):
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main([
"push", "snap_transport_1",
"--target", self.remote_dir,
"--target-dir", self.backup_dir,
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
res = json.loads(stdout.getvalue().strip())
self.assertEqual(res["status"], "success")
# Archive exists on remote
expected_remote = os.path.join(self.remote_dir, os.path.basename(self.archive_path))
self.assertTrue(os.path.isfile(expected_remote))
def test_cli_snapshot_auto_push(self):
dummy_f = os.path.join(self.test_dir, "auto.txt")
with open(dummy_f, "w") as f:
f.write("auto push test\n")
stdout = io.StringIO()
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", dummy_f,
"--push", self.remote_dir,
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
res = json.loads(stdout.getvalue().strip())
self.assertEqual(res["status"], "success")
self.assertIsNotNone(res["remote_push"])
self.assertEqual(res["remote_push"]["status"], "success")
if __name__ == "__main__":
unittest.main()