#!/usr/bin/env python3 """Unit tests for storage_manager.""" import sys import tempfile from pathlib import Path from urllib.parse import unquote sys.path.insert(0, str(Path(__file__).parent.parent)) def test_relative_path_format(): """Test relative path format for archive files.""" archive_dir = Path(tempfile.mkdtemp()) archive_file_path = archive_dir / "websites/TestSource/html/2024-01-15/article_001.html" archive_file_path.parent.mkdir(parents=True, exist_ok=True) archive_file_path.touch() stored_path = str(archive_file_path.relative_to(archive_dir)) assert not Path(stored_path).is_absolute() assert stored_path == "websites/TestSource/html/2024-01-15/article_001.html" retrieved_path = Path(stored_path) full_path = archive_dir / retrieved_path if not retrieved_path.is_absolute() else retrieved_path assert str(full_path) == str(archive_file_path) web_path = str(full_path.relative_to(archive_dir)) assert web_path == stored_path print(f" PASS: stored={stored_path}") def test_archive_file_url_generation(): """Test URL generation for archived files.""" archive_file_path = "websites/404 Media/html/2024-01-15/article_001.html" url = f"/archive-file/{archive_file_path}" assert url == "/archive-file/websites/404 Media/html/2024-01-15/article_001.html" decoded_path = unquote(archive_file_path) archive_dir = Path("/tmp/test_archives") full_path = archive_dir / decoded_path assert str(full_path) == str(archive_dir / "websites/404 Media/html/2024-01-15/article_001.html") print(f" PASS: url={url}") def test_multiple_sources(): """Test different sources get correct paths.""" archive_dir = Path(tempfile.mkdtemp()) for source in ["404 Media", "TestSource", "Another Source"]: archive_file_path = archive_dir / f"websites/{source}/html/2024-01-15/article_001.html" archive_file_path.parent.mkdir(parents=True, exist_ok=True) stored_path = str(archive_file_path.relative_to(archive_dir)) parts = Path(stored_path).parts assert parts[0] == "websites" assert parts[1] == source assert parts[2] == "html" print(f" PASS: source='{source}' path={stored_path}") if __name__ == "__main__": test_relative_path_format() test_archive_file_url_generation() test_multiple_sources() print("\nAll storage_manager tests passed!")