Voucher-Generator / test_deployment.py
Sidd-mukho77
Switch to native Gradio File component for PDF upload and preview
2eea0cb
Raw History Blame Contribute Delete
5.97 kB
#!/usr/bin/env python3
"""
Deployment Test Script for HuggingFace Spaces
Tests if the app can start without dependency errors
"""
import sys
import subprocess
import importlib
from pathlib import Path
def test_imports():
"""Test that all critical imports work"""
print("πŸ” Testing critical imports...")
critical_imports = [
"gradio",
"google.genai",
"reportlab",
"pypdf",
"pandas",
"PIL",
"dotenv"
]
failed = []
for module in critical_imports:
try:
importlib.import_module(module)
print(f" βœ… {module}")
except ImportError as e:
print(f" ❌ {module}: {e}")
failed.append((module, str(e)))
if failed:
print("\n❌ Import test failed!")
for module, error in failed:
print(f" - {module}: {error}")
return False
print("βœ… All imports successful!\n")
return True
def test_gradio_version():
"""Test that Gradio version matches README.md"""
print("πŸ” Testing Gradio version compatibility...")
import gradio as gr
# Read README.md to get expected version
readme_path = Path(__file__).parent / "README.md"
expected_version = None
if readme_path.exists():
with open(readme_path, 'r') as f:
for line in f:
if line.strip().startswith('sdk_version:'):
expected_version = line.split(':')[1].strip()
break
actual_version = gr.__version__
if expected_version:
print(f" Expected (README.md): {expected_version}")
print(f" Actual (installed): {actual_version}")
if actual_version == expected_version:
print(" βœ… Versions match!")
else:
print(" ⚠️ Version mismatch (may still work)")
else:
print(f" ℹ️ Installed version: {actual_version}")
# Test built-in File component for PDF support
try:
test_file = gr.File(label="Test", file_types=[".pdf"])
print(" βœ… Gradio File component supports PDF files")
except Exception as e:
print(f" ❌ File component error: {e}")
return False
print()
return True
def test_app_syntax():
"""Test that app.py has no syntax errors"""
print("πŸ” Testing app.py syntax...")
app_path = Path(__file__).parent / "app.py"
if not app_path.exists():
print(" ❌ app.py not found!")
return False
try:
with open(app_path, 'r') as f:
compile(f.read(), str(app_path), 'exec')
print(" βœ… No syntax errors\n")
return True
except SyntaxError as e:
print(f" ❌ Syntax error: {e}\n")
return False
def test_dependencies():
"""Test that requirements.txt dependencies can be installed"""
print("πŸ” Testing requirements.txt...")
req_path = Path(__file__).parent / "requirements.txt"
if not req_path.exists():
print(" ❌ requirements.txt not found!")
return False
with open(req_path, 'r') as f:
deps = [line.strip() for line in f if line.strip() and not line.startswith('#')]
print(f" Found {len(deps)} dependencies:")
for dep in deps:
print(f" - {dep}")
print(" βœ… Requirements file valid\n")
return True
def test_env_vars():
"""Check for required environment variables"""
print("πŸ” Checking environment setup...")
import os
required_vars = ["GEMINI_API_KEY"]
optional_vars = ["SEARCH_API_KEY", "SEARCH_ENGINE_ID"]
missing_required = []
for var in required_vars:
if os.getenv(var):
print(f" βœ… {var} is set")
else:
print(f" ⚠️ {var} NOT set (REQUIRED for app to work)")
missing_required.append(var)
for var in optional_vars:
if os.getenv(var):
print(f" βœ… {var} is set")
else:
print(f" ℹ️ {var} not set (optional)")
if missing_required:
print(f"\n ⚠️ Missing required variables: {', '.join(missing_required)}")
print(" ℹ️ App will fail at runtime without these!")
print()
return len(missing_required) == 0
def test_output_directory():
"""Check if output directory exists"""
print("πŸ” Checking output directory...")
output_dir = Path(__file__).parent / "output"
if output_dir.exists():
print(f" βœ… Output directory exists: {output_dir}")
else:
print(f" ℹ️ Output directory will be created at runtime")
print()
return True
def main():
"""Run all deployment tests"""
print("=" * 60)
print("πŸš€ HuggingFace Spaces Deployment Test")
print("=" * 60)
print()
tests = [
("Dependencies", test_dependencies),
("Python Imports", test_imports),
("Gradio Version", test_gradio_version),
("App Syntax", test_app_syntax),
("Environment Variables", test_env_vars),
("Output Directory", test_output_directory),
]
results = []
for name, test_func in tests:
try:
passed = test_func()
results.append((name, passed))
except Exception as e:
print(f" ❌ {name} test crashed: {e}\n")
results.append((name, False))
# Summary
print("=" * 60)
print("πŸ“Š Test Summary")
print("=" * 60)
passed = sum(1 for _, p in results if p)
total = len(results)
for name, result in results:
status = "βœ… PASS" if result else "❌ FAIL"
print(f" {status}: {name}")
print()
print(f"Results: {passed}/{total} tests passed")
if passed == total:
print("\nπŸŽ‰ All tests passed! Safe to deploy to HuggingFace Spaces.")
return 0
else:
print("\n⚠️ Some tests failed. Fix issues before deploying.")
return 1
if __name__ == "__main__":
sys.exit(main())