-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
134 lines (108 loc) Β· 4.44 KB
/
test_api.py
File metadata and controls
134 lines (108 loc) Β· 4.44 KB
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
#!/usr/bin/env python3
"""
Test script for SMS Spam Detection Application
This script demonstrates the spam detection functionality
"""
import requests
import json
import time
# Test SMS messages
test_messages = [
"Congratulations! You've won $1000! Click here to claim your prize now!",
"Hey, how are you doing? Want to grab coffee later?",
"URGENT: Your account will be closed in 24 hours. Call now to prevent this!",
"Thanks for the meeting today. Let me know if you need anything else.",
"FREE! Win a new iPhone! Text STOP to opt out. Limited time offer!",
"Can you pick up some milk on your way home?",
"You have been selected for a special promotion! Act now!",
"See you at the gym at 6 PM?",
"URGENT: Your credit card has been compromised. Click here immediately!",
"Happy birthday! Hope you have a wonderful day!"
]
def test_prediction_api():
"""Test the prediction API endpoint"""
print("π§ͺ Testing SMS Spam Detection API")
print("=" * 50)
base_url = "http://localhost:5001"
for i, message in enumerate(test_messages, 1):
print(f"\nπ± Test {i}: {message[:50]}...")
try:
response = requests.post(
f"{base_url}/predict",
json={"sms_text": message},
headers={"Content-Type": "application/json"}
)
if response.status_code == 200:
data = response.json()
label = data['label']
confidence = data['confidence']
# Color coding for output
if label == 'spam':
print(f" π΄ Result: SPAM (Confidence: {confidence:.2f})")
else:
print(f" π’ Result: NOT SPAM (Confidence: {confidence:.2f})")
else:
print(f" β Error: {response.status_code}")
except requests.exceptions.ConnectionError:
print(" β Error: Could not connect to server. Make sure the Flask app is running.")
return False
except Exception as e:
print(f" β Error: {e}")
return True
def test_messages_api():
"""Test the messages API endpoint"""
print("\n\nπ Testing Messages API")
print("=" * 50)
base_url = "http://localhost:5001"
try:
# Test getting messages
response = requests.get(f"{base_url}/messages")
if response.status_code == 200:
data = response.json()
print(f"β
Total messages: {data['total_count']}")
print(f"β
Current page: {data['page']}")
print(f"β
Total pages: {data['total_pages']}")
if data['messages']:
print("\nπ Recent messages:")
for msg in data['messages'][:3]: # Show first 3
print(f" β’ {msg['sms_text'][:40]}... -> {msg['prediction']}")
else:
print(f"β Error: {response.status_code}")
except Exception as e:
print(f"β Error: {e}")
def test_stats_api():
"""Test the stats API endpoint"""
print("\n\nπ Testing Stats API")
print("=" * 50)
base_url = "http://localhost:5001"
try:
response = requests.get(f"{base_url}/stats")
if response.status_code == 200:
data = response.json()
print(f"β
Total messages: {data['total_messages']}")
print(f"β
Spam messages: {data['spam_count']}")
print(f"β
Not spam messages: {data['not_spam_count']}")
print(f"β
Spam percentage: {data['spam_percentage']:.1f}%")
else:
print(f"β Error: {response.status_code}")
except Exception as e:
print(f"β Error: {e}")
def main():
"""Main test function"""
print("π SMS Spam Detection - API Test Suite")
print("=" * 60)
print("Make sure the Flask application is running on http://localhost:5001")
print("Run: python app.py")
print("=" * 60)
# Wait a moment for user to start the server
time.sleep(2)
# Run tests
if test_prediction_api():
test_messages_api()
test_stats_api()
print("\n\nπ All tests completed!")
print("Visit http://localhost:5001 to see the web interface")
else:
print("\nβ Tests failed. Please start the Flask application first.")
if __name__ == "__main__":
main()