File size: 5,213 Bytes
472e2e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python3
"""
Test script for the Backend Code Generation API
===============================================

Simple test script to verify the API is working correctly.
"""

import requests
import json
import time
import os

# API base URL
BASE_URL = "http://localhost:8000"

def test_health():
    """Test the health endpoint"""
    print("Testing health endpoint...")
    response = requests.get(f"{BASE_URL}/health")
    print(f"Status: {response.status_code}")
    print(f"Response: {response.json()}")
    return response.status_code == 200

def test_generate_code():
    """Test code generation"""
    print("\nTesting code generation...")
    
    # Test request
    request_data = {
        "description": "Simple REST API for task management",
        "framework": "fastapi",
        "language": "python",
        "requirements": [
            "User authentication",
            "Task CRUD operations",
            "Task status tracking"
        ],
        "project_name": "task-manager-api"
    }
    
    # Submit generation request
    response = requests.post(f"{BASE_URL}/api/v1/generate", json=request_data)
    print(f"Generation request status: {response.status_code}")
    
    if response.status_code == 200:
        result = response.json()
        task_id = result["task_id"]
        print(f"Task ID: {task_id}")
        
        # Poll for completion
        print("Polling for completion...")
        for i in range(30):  # Wait up to 5 minutes
            status_response = requests.get(f"{BASE_URL}/api/v1/status/{task_id}")
            if status_response.status_code == 200:
                status = status_response.json()
                print(f"Status: {status['status']} - {status['message']} ({status['progress']}%)")
                
                if status["status"] == "completed":
                    print("βœ… Generation completed!")
                    if status.get("download_url"):
                        print(f"Download URL: {status['download_url']}")
                    return True
                elif status["status"] == "failed":
                    print(f"❌ Generation failed: {status.get('error', 'Unknown error')}")
                    return False
            else:
                print(f"Failed to get status: {status_response.status_code}")
                return False
            
            time.sleep(10)  # Wait 10 seconds between polls
        
        print("⏰ Timeout waiting for completion")
        return False
    else:
        print(f"❌ Generation request failed: {response.text}")
        return False

def test_frameworks():
    """Test frameworks endpoint"""
    print("\nTesting frameworks endpoint...")
    response = requests.get(f"{BASE_URL}/api/v1/frameworks")
    print(f"Status: {response.status_code}")
    if response.status_code == 200:
        frameworks = response.json()
        print(f"Supported frameworks: {len(frameworks['frameworks'])}")
        for fw in frameworks['frameworks']:
            print(f"  - {fw['name']} ({fw['language']})")
        return True
    return False

def test_examples():
    """Test examples endpoint"""
    print("\nTesting examples endpoint...")
    response = requests.get(f"{BASE_URL}/api/v1/examples")
    print(f"Status: {response.status_code}")
    if response.status_code == 200:
        examples = response.json()
        print(f"Available examples: {len(examples['examples'])}")
        for ex in examples['examples']:
            print(f"  - {ex['name']}")
        return True
    return False

def main():
    """Run all tests"""
    print("πŸš€ Testing Backend Code Generation API")
    print("=" * 50)
    
    # Check if API is running
    try:
        response = requests.get(f"{BASE_URL}/", timeout=5)
        if response.status_code != 200:
            print("❌ API is not running. Please start it with: python api_service.py")
            return
    except requests.exceptions.RequestException:
        print("❌ Cannot connect to API. Please start it with: python api_service.py")
        return
    
    print("βœ… API is running")
    
    # Run tests
    tests = [
        ("Health Check", test_health),
        ("Frameworks List", test_frameworks),
        ("Examples List", test_examples),
        ("Code Generation", test_generate_code),
    ]
    
    results = []
    for test_name, test_func in tests:
        print(f"\n{'='*20} {test_name} {'='*20}")
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"❌ Test failed with error: {e}")
            results.append((test_name, False))
    
    # Summary
    print(f"\n{'='*50}")
    print("πŸ“Š Test Results Summary:")
    print("=" * 50)
    
    passed = 0
    for test_name, result in results:
        status = "βœ… PASS" if result else "❌ FAIL"
        print(f"{test_name}: {status}")
        if result:
            passed += 1
    
    print(f"\nPassed: {passed}/{len(results)} tests")
    
    if passed == len(results):
        print("πŸŽ‰ All tests passed!")
    else:
        print("⚠️  Some tests failed. Check the output above for details.")

if __name__ == "__main__":
    main()