Files
Projektarbeit-MYP/backend/test_development.py

396 lines
11 KiB
Python

#!/usr/bin/env python3
"""
Test-Script für MYP Development-Setup
Testet alle Komponenten ohne /opt/myp-Deployment
Verwendung:
python test_development.py
python test_development.py --verbose
"""
import os
import sys
import subprocess
import argparse
import time
import requests
from pathlib import Path
def print_test_banner():
"""Zeigt den Test-Banner"""
banner = f"""
{'='*70}
🧪 MYP DEVELOPMENT TESTS
{'='*70}
📁 Arbeitsverzeichnis: {os.getcwd()}
🐍 Python-Version: {sys.version.split()[0]}
🌐 Test-Umgebung: Development (Local)
{'='*70}
"""
print(banner)
def test_python_environment():
"""Testet die Python-Umgebung"""
print("🐍 Teste Python-Environment...")
tests = []
# Python-Version
if sys.version_info >= (3, 8):
tests.append("✅ Python-Version OK")
else:
tests.append("❌ Python-Version zu alt")
return False
# Erforderliche Module
required_modules = [
'flask', 'sqlalchemy', 'werkzeug', 'jinja2',
'wtforms', 'flask_login', 'flask_wtf'
]
for module in required_modules:
try:
__import__(module)
tests.append(f"{module}")
except ImportError:
tests.append(f"{module} fehlt")
return False
for test in tests:
print(f" {test}")
print("✅ Python-Environment OK\n")
return True
def test_file_structure():
"""Testet die Dateistruktur"""
print("📁 Teste Dateistruktur...")
required_files = [
'app.py',
'models.py',
'utils/settings.py',
'requirements.txt',
'package.json',
'tailwind.config.js'
]
required_dirs = [
'templates',
'static',
'blueprints',
'utils',
'instance'
]
tests = []
all_ok = True
# Dateien prüfen
for file in required_files:
if os.path.exists(file):
tests.append(f"{file}")
else:
tests.append(f"{file} fehlt")
all_ok = False
# Verzeichnisse prüfen
for dir in required_dirs:
if os.path.exists(dir):
tests.append(f"{dir}/")
else:
tests.append(f"{dir}/ fehlt")
all_ok = False
for test in tests:
print(f" {test}")
if all_ok:
print("✅ Dateistruktur OK\n")
else:
print("❌ Dateistruktur unvollständig\n")
return all_ok
def test_node_environment():
"""Testet die Node.js-Umgebung"""
print("📦 Teste Node.js-Environment...")
tests = []
# Node.js verfügbar
try:
result = subprocess.run(['node', '--version'], capture_output=True, text=True)
tests.append(f"✅ Node.js {result.stdout.strip()}")
except FileNotFoundError:
tests.append("❌ Node.js nicht gefunden")
return False
# npm verfügbar
try:
result = subprocess.run(['npm', '--version'], capture_output=True, text=True)
tests.append(f"✅ npm {result.stdout.strip()}")
except FileNotFoundError:
tests.append("❌ npm nicht gefunden")
return False
# node_modules vorhanden
if os.path.exists('node_modules'):
tests.append("✅ node_modules vorhanden")
else:
tests.append("⚠️ node_modules fehlt - wird installiert")
try:
subprocess.run(['npm', 'install'], check=True, capture_output=True)
tests.append("✅ node_modules installiert")
except subprocess.CalledProcessError:
tests.append("❌ npm install fehlgeschlagen")
return False
for test in tests:
print(f" {test}")
print("✅ Node.js-Environment OK\n")
return True
def test_css_build():
"""Testet den CSS-Build"""
print("🎨 Teste CSS-Build...")
tests = []
# Tailwind-Config vorhanden
if os.path.exists('tailwind.config.js'):
tests.append("✅ tailwind.config.js")
else:
tests.append("❌ tailwind.config.js fehlt")
return False
# Input-CSS vorhanden
if os.path.exists('static/css/input.css'):
tests.append("✅ input.css")
else:
tests.append("❌ input.css fehlt")
return False
# CSS bauen
try:
subprocess.run(['npm', 'run', 'build'], check=True, capture_output=True)
tests.append("✅ CSS-Build erfolgreich")
except subprocess.CalledProcessError as e:
tests.append(f"❌ CSS-Build fehlgeschlagen: {e}")
return False
# Output-CSS prüfen
if os.path.exists('static/css/tailwind.min.css'):
file_size = os.path.getsize('static/css/tailwind.min.css')
tests.append(f"✅ tailwind.min.css ({file_size} Bytes)")
else:
tests.append("❌ tailwind.min.css nicht erstellt")
return False
for test in tests:
print(f" {test}")
print("✅ CSS-Build OK\n")
return True
def test_database_setup():
"""Testet die Datenbank-Einrichtung"""
print("🗄️ Teste Datenbank-Setup...")
tests = []
# Instance-Verzeichnis
if not os.path.exists('instance'):
os.makedirs('instance')
tests.append("✅ instance/ erstellt")
else:
tests.append("✅ instance/ vorhanden")
# Datenbank-Import testen
try:
from models import init_database, User, Printer, Job
tests.append("✅ Datenbank-Modelle importiert")
except ImportError as e:
tests.append(f"❌ Datenbank-Import fehlgeschlagen: {e}")
return False
# Datenbank initialisieren (Test)
try:
# Setze Test-Environment
os.environ['FLASK_ENV'] = 'development'
os.environ['TESTING'] = 'true'
# Initialisiere Datenbank
init_database()
tests.append("✅ Datenbank initialisiert")
except Exception as e:
tests.append(f"❌ Datenbank-Initialisierung fehlgeschlagen: {e}")
return False
for test in tests:
print(f" {test}")
print("✅ Datenbank-Setup OK\n")
return True
def test_flask_app():
"""Testet die Flask-App"""
print("🌐 Teste Flask-App...")
tests = []
# App-Import
try:
# Setze Development-Environment
os.environ['FLASK_ENV'] = 'development'
os.environ['FLASK_DEBUG'] = '1'
os.environ['USE_PRODUCTION_CONFIG'] = 'false'
from app import create_app
tests.append("✅ Flask-App importiert")
except ImportError as e:
tests.append(f"❌ Flask-App-Import fehlgeschlagen: {e}")
return False
# App-Erstellung
try:
app = create_app()
tests.append("✅ Flask-App erstellt")
except Exception as e:
tests.append(f"❌ Flask-App-Erstellung fehlgeschlagen: {e}")
return False
# Test-Client
try:
with app.test_client() as client:
# Health-Check
response = client.get('/api/health')
if response.status_code == 200:
tests.append("✅ Health-Check OK")
else:
tests.append(f"⚠️ Health-Check: {response.status_code}")
except Exception as e:
tests.append(f"❌ Test-Client fehlgeschlagen: {e}")
return False
for test in tests:
print(f" {test}")
print("✅ Flask-App OK\n")
return True
def test_server_start():
"""Testet den Server-Start (kurzer Test)"""
print("🚀 Teste Server-Start...")
tests = []
# Setze Test-Port
test_port = 5001
os.environ['FLASK_PORT'] = str(test_port)
os.environ['FLASK_HOST'] = '127.0.0.1'
# Starte Server im Hintergrund
try:
process = subprocess.Popen([
sys.executable, 'setup_development.py',
'--port', str(test_port), '--skip-deps', '--skip-css'
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
tests.append("✅ Server-Prozess gestartet")
# Warte kurz
time.sleep(3)
# Teste Verbindung
try:
response = requests.get(f'http://127.0.0.1:{test_port}/api/health', timeout=5)
if response.status_code == 200:
tests.append("✅ Server erreichbar")
else:
tests.append(f"⚠️ Server-Response: {response.status_code}")
except requests.exceptions.RequestException as e:
tests.append(f"⚠️ Server nicht erreichbar: {e}")
# Server stoppen
process.terminate()
process.wait(timeout=5)
tests.append("✅ Server gestoppt")
except Exception as e:
tests.append(f"❌ Server-Test fehlgeschlagen: {e}")
return False
for test in tests:
print(f" {test}")
print("✅ Server-Start OK\n")
return True
def run_all_tests(verbose=False):
"""Führt alle Tests aus"""
print_test_banner()
tests = [
("Python-Environment", test_python_environment),
("Dateistruktur", test_file_structure),
("Node.js-Environment", test_node_environment),
("CSS-Build", test_css_build),
("Datenbank-Setup", test_database_setup),
("Flask-App", test_flask_app),
("Server-Start", test_server_start)
]
results = []
for test_name, test_func in tests:
try:
result = test_func()
results.append((test_name, result))
except Exception as e:
print(f"{test_name} - EXCEPTION: {e}")
results.append((test_name, False))
if verbose:
import traceback
traceback.print_exc()
# Zusammenfassung
print("="*70)
print("📊 TEST-ZUSAMMENFASSUNG")
print("="*70)
passed = 0
failed = 0
for test_name, result in results:
if result:
print(f"{test_name}")
passed += 1
else:
print(f"{test_name}")
failed += 1
print(f"\n📈 ERGEBNIS: {passed} erfolgreich, {failed} fehlgeschlagen")
if failed == 0:
print("🎉 ALLE TESTS BESTANDEN - Development-Setup ist bereit!")
return True
else:
print("🛑 TESTS FEHLGESCHLAGEN - behebe die Probleme vor dem Start")
return False
def main():
"""Haupt-Test-Funktion"""
parser = argparse.ArgumentParser(description='MYP Development Tests')
parser.add_argument('--verbose', '-v', action='store_true', help='Verbose-Ausgabe')
args = parser.parse_args()
success = run_all_tests(verbose=args.verbose)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()