AnsysLink/test/test_api_mesh_generation.py

169 lines
5.7 KiB
Python

"""
Test mesh generation API endpoints
"""
import pytest
import json
import time
import os
from pathlib import Path
from backend.utils.state_manager import state_manager
from backend.models.data_models import UploadedFile
from datetime import datetime
@pytest.fixture
def client():
"""Create test client"""
from app import create_app
app = create_app()
app.config['TESTING'] = True
with app.test_client() as client:
with app.app_context():
# Clear state for clean test
state_manager.clear_current_file()
state_manager.clear_session_data()
yield client
@pytest.fixture
def test_file_path():
"""Get path to test STEP file"""
base_dir = Path(__file__).parent.parent
test_file = base_dir / "resource" / "blade.step"
assert test_file.exists(), f"Test file not found: {test_file}"
return str(test_file)
def test_generate_mesh_no_file(client):
"""Test mesh generation without uploaded file"""
response = client.post('/api/mesh/generate')
assert response.status_code == 400
data = json.loads(response.data)
assert data['success'] is False
assert 'No file uploaded' in data['error']
def test_generate_mesh_simulation_mode(client, test_file_path):
"""Test complete mesh generation workflow in simulation mode"""
# Upload file
with open(test_file_path, 'rb') as f:
response = client.post('/api/upload',
data={'file': (f, 'blade.step')},
content_type='multipart/form-data')
assert response.status_code == 200
upload_data = json.loads(response.data)
assert upload_data['success'] is True
# Start mesh generation
response = client.post('/api/mesh/generate',
data=json.dumps({'simulation_mode': True}),
content_type='application/json')
assert response.status_code == 202 # Accepted
data = json.loads(response.data)
assert data['success'] is True
assert data['message'] == 'Mesh generation started'
assert data['simulation_mode'] is True
# Wait for completion
max_wait_time = 15 # 15 seconds should be enough for simulation
start_time = time.time()
while time.time() - start_time < max_wait_time:
response = client.get('/api/mesh/progress')
progress_data = json.loads(response.data)
if progress_data['status'] in ['COMPLETED', 'ERROR']:
break
time.sleep(1)
# Verify completion
assert progress_data['status'] == 'COMPLETED'
# Check mesh result
response = client.get('/api/mesh/result')
assert response.status_code == 200
result_data = json.loads(response.data)
assert result_data['success'] is True
assert result_data['result']['element_count'] > 0
assert result_data['result']['node_count'] > 0
print(f"Mesh generation completed successfully:")
print(f" - Elements: {result_data['result']['element_count']}")
print(f" - Nodes: {result_data['result']['node_count']}")
def test_api_endpoints_integration(client, test_file_path):
"""Test complete API workflow integration"""
print("\n=== Testing Complete API Workflow ===")
# Step 1: Check health
response = client.get('/api/health')
assert response.status_code == 200
health_data = json.loads(response.data)
assert health_data['success'] is True
print("Health check passed")
# Step 2: Check system state (no file)
response = client.get('/api/system/state')
assert response.status_code == 200
state_data = json.loads(response.data)
assert state_data['state']['current_file'] is None
assert state_data['state']['is_ready_for_processing'] is False
print("Initial state check passed")
# Step 3: Upload file
with open(test_file_path, 'rb') as f:
response = client.post('/api/upload',
data={'file': (f, 'blade.step')},
content_type='multipart/form-data')
assert response.status_code == 200
print("File upload passed")
# Step 4: Check readiness
response = client.get('/api/mesh/ready')
assert response.status_code == 200
ready_data = json.loads(response.data)
assert ready_data['ready'] is True
print("Mesh readiness check passed")
# Step 5: Start mesh generation
response = client.post('/api/mesh/generate',
data=json.dumps({'simulation_mode': True}),
content_type='application/json')
assert response.status_code == 202
print("Mesh generation started")
# Step 6: Monitor progress until completion
completion_time = None
for i in range(20): # 20 second timeout
response = client.get('/api/mesh/progress')
progress_data = json.loads(response.data)
if progress_data['status'] == 'COMPLETED':
completion_time = progress_data.get('processing_time', 0)
break
elif progress_data['status'] == 'ERROR':
pytest.fail(f"Processing failed: {progress_data.get('error_message', 'Unknown error')}")
time.sleep(1)
assert completion_time is not None
print(f"Mesh generation completed in {completion_time:.1f}s")
# Step 7: Get final results
response = client.get('/api/mesh/result')
assert response.status_code == 200
result_data = json.loads(response.data)
assert result_data['success'] is True
print(f"Final mesh result: {result_data['result']['element_count']} elements")
print("=== Complete API Workflow Test Passed ===\n")
if __name__ == "__main__":
print("Testing Mesh Generation API Endpoints...")
print("Run with: pytest test/test_api_mesh_generation.py -v")