-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
225 lines (187 loc) · 7.5 KB
/
main.py
File metadata and controls
225 lines (187 loc) · 7.5 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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python3
"""
Endpoint Performance Tester
A tool for testing API endpoints and measuring their performance
"""
import asyncio
import argparse
import sys
from pathlib import Path
from typing import Optional
from config.logging_config import LoggingConfig, PerformanceLogger
from controllers.test_manager import TestManager
from views.result_display import ResultDisplay
class EndpointTesterApp:
"""Main application class for endpoint testing"""
def __init__(self):
self.logging_config = LoggingConfig()
self.logger = self.logging_config.setup_logger()
self.performance_logger = PerformanceLogger(
self.logging_config.setup_performance_logger()
)
self.test_manager = TestManager(self.logger)
self.result_display = ResultDisplay(self.logger)
async def run_test_from_config(self, config_file: str, detailed: bool = False):
"""Run tests from configuration file"""
try:
# Load test suite from file
test_suite = self.test_manager.load_test_suite_from_file(config_file)
self.test_manager.add_test_suite(test_suite)
# Log test start
self.performance_logger.log_test_start(
test_suite.name,
test_suite.test_duration_seconds,
test_suite.concurrent_requests
)
# Run the test
result = await self.test_manager.run_test_suite(test_suite.name)
if result:
# Log test end
self.performance_logger.log_test_end(
test_suite.name,
result.total_duration_seconds
)
# Display results
self.result_display.display_test_suite_result(result, detailed)
# Export results
self._export_results(result)
return result
else:
self.logger.error("Test execution failed")
return None
except Exception as e:
self.logger.error(f"Error running test: {str(e)}")
return None
async def run_interactive_mode(self):
"""Run interactive mode for testing"""
print("=== Endpoint Performance Tester ===")
print("Interactive Mode")
print("Type 'help' for available commands")
while True:
try:
command = input("\n> ").strip().lower()
if command in ['exit', 'quit', 'q']:
print("Goodbye!")
break
elif command == 'help':
self._show_help()
elif command == 'list':
self._list_test_suites()
elif command.startswith('load '):
config_file = command.split(' ', 1)[1]
await self._load_and_run_test(config_file)
elif command.startswith('create_sample'):
self._create_sample_config()
elif command == 'clear':
self.test_manager.test_suites.clear()
print("Test suites cleared")
else:
print("Unknown command. Type 'help' for available commands")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
self.logger.error(f"Error in interactive mode: {str(e)}")
print(f"Error: {str(e)}")
def _show_help(self):
"""Show help information"""
print("\nAvailable commands:")
print(" help - Show this help")
print(" list - List loaded test suites")
print(" load <config_file> - Load and run test from config file")
print(" create_sample - Create sample configuration file")
print(" clear - Clear all loaded test suites")
print(" exit/quit/q - Exit the application")
def _list_test_suites(self):
"""List loaded test suites"""
suites = self.test_manager.list_test_suites()
if suites:
print(f"\nLoaded test suites ({len(suites)}):")
for suite in suites:
print(f" - {suite}")
else:
print("No test suites loaded")
async def _load_and_run_test(self, config_file: str):
"""Load and run test from config file"""
try:
result = await self.run_test_from_config(config_file, detailed=True)
if result:
print(f"\nTest completed successfully!")
else:
print(f"\nTest failed!")
except Exception as e:
print(f"Error: {str(e)}")
def _create_sample_config(self):
"""Create sample configuration file"""
sample_file = "sample_test_config.json"
self.test_manager.create_sample_config(sample_file)
print(f"Sample configuration created: {sample_file}")
def _export_results(self, result):
"""Export test results to files"""
timestamp = result.start_time
from datetime import datetime
timestamp_str = datetime.fromtimestamp(timestamp).strftime('%Y%m%d_%H%M%S')
# Export to JSON
json_file = f"test_results_{timestamp_str}.json"
self.result_display.export_results_to_json(result, json_file)
# Export to CSV
csv_file = f"test_results_{timestamp_str}.csv"
self.result_display.export_results_to_csv(result, csv_file)
# Generate report
report = self.result_display.generate_performance_report(result)
report_file = f"test_report_{timestamp_str}.md"
with open(report_file, 'w', encoding='utf-8') as f:
f.write(report)
print(f"\nResults exported to:")
print(f" - {json_file}")
print(f" - {csv_file}")
print(f" - {report_file}")
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Endpoint Performance Tester",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python main.py --config sample_config.json
python main.py --interactive
python main.py --config api_tests.json --detailed
"""
)
parser.add_argument(
'--config', '-c',
type=str,
help='Configuration file to run tests from'
)
parser.add_argument(
'--interactive', '-i',
action='store_true',
help='Run in interactive mode'
)
parser.add_argument(
'--detailed', '-d',
action='store_true',
help='Show detailed results including individual request metrics'
)
parser.add_argument(
'--create-sample',
action='store_true',
help='Create a sample configuration file and exit'
)
args = parser.parse_args()
# Create app instance
app = EndpointTesterApp()
if args.create_sample:
app._create_sample_config()
return
if args.interactive:
# Run interactive mode
asyncio.run(app.run_interactive_mode())
elif args.config:
# Run from config file
asyncio.run(app.run_test_from_config(args.config, args.detailed))
else:
# Show help if no arguments
parser.print_help()
if __name__ == "__main__":
main()