pdf-4 / test_fixes.py
fokan's picture
Initial commit with static file serving and inline PDF viewing
623e14e
#!/usr/bin/env python3
"""
Quick test for the fixes applied to the template conversion system
Tests Arial font path and PDF generation fixes
"""
import os
import sys
from pathlib import Path
import tempfile
# Add current directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_arial_font_path():
"""Test Arial font path resolution"""
print("🔤 Testing Arial font path resolution...")
# Get script directory
script_dir = Path(__file__).parent.absolute()
print(f" • Script directory: {script_dir}")
# Check Arial font path (same directory as script)
arial_path = script_dir / "arial.ttf"
print(f" • Looking for Arial at: {arial_path}")
if arial_path.exists():
print(f" ✅ Arial font found!")
print(f" • File size: {arial_path.stat().st_size} bytes")
return True
else:
print(f" ❌ Arial font not found!")
print(f" • Contents of script directory:")
for file in script_dir.iterdir():
if file.suffix.lower() in ['.ttf', '.otf', '.docx', '.py']:
print(f" - {file.name}")
return False
def test_template_path():
"""Test template.docx path"""
print("\n📄 Testing template.docx path...")
script_dir = Path(__file__).parent.absolute()
template_path = script_dir / "template.docx"
print(f" • Looking for template at: {template_path}")
if template_path.exists():
print(f" ✅ Template found!")
print(f" • File size: {template_path.stat().st_size} bytes")
return True
else:
print(f" ❌ Template not found!")
return False
def test_font_setup_function():
"""Test the setup_local_arial_font function"""
print("\n🔧 Testing setup_local_arial_font function...")
try:
from app import setup_local_arial_font
result = setup_local_arial_font()
if result:
print(" ✅ Font setup function works correctly")
else:
print(" ⚠️ Font setup function returned False (may still work)")
return True
except Exception as e:
print(f" ❌ Font setup function failed: {e}")
return False
def test_pdf_detection_logic():
"""Test PDF file detection logic"""
print("\n📋 Testing PDF detection logic...")
try:
# Create a temporary directory with some test files
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Create some test files
(temp_path / "test.txt").write_text("test")
(temp_path / "document.pdf").write_text("fake pdf")
(temp_path / "another.pdf").write_text("another fake pdf")
# Test the logic
all_files = list(temp_path.iterdir())
pdf_files = [f for f in all_files if f.suffix.lower() == '.pdf']
print(f" • Total files: {len(all_files)}")
print(f" • PDF files found: {len(pdf_files)}")
print(f" • PDF files: {[f.name for f in pdf_files]}")
if len(pdf_files) >= 1:
print(" ✅ PDF detection logic works correctly")
return True
else:
print(" ❌ PDF detection logic failed")
return False
except Exception as e:
print(f" ❌ PDF detection test failed: {e}")
return False
def test_fontconfig_creation():
"""Test fontconfig creation with correct paths"""
print("\n⚙️ Testing fontconfig creation...")
try:
from app import create_fontconfig
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Test fontconfig creation
config_home = create_fontconfig(temp_path)
# Check if fonts.conf was created
fonts_conf = temp_path / ".config" / "fontconfig" / "fonts.conf"
if fonts_conf.exists():
print(" ✅ fonts.conf created successfully")
# Check content
content = fonts_conf.read_text()
script_dir = Path(__file__).parent.absolute()
if str(script_dir) in content:
print(f" ✅ Script directory included: {script_dir}")
else:
print(f" ⚠️ Script directory not found in config")
if "Arial" in content:
print(" ✅ Arial font configuration found")
else:
print(" ⚠️ Arial font configuration not found")
return True
else:
print(" ❌ fonts.conf was not created")
return False
except Exception as e:
print(f" ❌ Fontconfig creation test failed: {e}")
return False
def main():
"""Run all fix tests"""
print("🧪 Testing Applied Fixes")
print("=" * 50)
tests = [
("Arial Font Path", test_arial_font_path),
("Template Path", test_template_path),
("Font Setup Function", test_font_setup_function),
("PDF Detection Logic", test_pdf_detection_logic),
("Fontconfig Creation", test_fontconfig_creation),
]
results = {}
for test_name, test_func in tests:
try:
results[test_name] = test_func()
except Exception as e:
print(f"❌ {test_name} failed with exception: {e}")
results[test_name] = False
# Summary
print("\n" + "=" * 50)
print("📊 Fix Test Results:")
passed = 0
total = len(tests)
for test_name, result in results.items():
status = "✅ PASS" if result else "❌ FAIL"
print(f" {status} - {test_name}")
if result:
passed += 1
print(f"\n🎯 Overall: {passed}/{total} tests passed ({passed/total*100:.1f}%)")
if passed == total:
print("🌟 All fixes working correctly!")
elif passed >= total * 0.8:
print("👍 Most fixes working. Minor issues may remain.")
else:
print("⚠️ Several fixes need attention.")
print("\n💡 Key fixes applied:")
print(" • Arial font path now relative to Python script")
print(" • PDF detection improved to find any .pdf file")
print(" • Fontconfig includes local fonts directory")
print(" • Enhanced environment variables for fonts")
return passed >= total * 0.8
if __name__ == "__main__":
success = main()
print(f"\n{'✅ Fixes are working!' if success else '❌ Some fixes need attention.'}")
sys.exit(0 if success else 1)