-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
252 lines (206 loc) · 7.63 KB
/
main.py
File metadata and controls
252 lines (206 loc) · 7.63 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
"""
Java Mock Generator CLI
Analyzes Java legacy code and generates meaningful Mockito mocks
"""
import argparse
import sys
import os
from pathlib import Path
from java_parser import JavaParser
from analyzer import JavaAnalyzer
from mock_generator import MockitoGenerator
from output_formatter import ConsoleFormatter
from api_analyzer import APIAnalyzer
from api_output_formatter import APIOutputFormatter
def ensure_output_directory(output_path: str, dir_name: str) -> str:
"""Ensure output directory exists and return full path"""
if os.path.isabs(output_path):
# Absolute path provided
full_path = output_path
else:
# Relative path - create in project subdirectory
output_dir = os.path.join(os.getcwd(), dir_name)
os.makedirs(output_dir, exist_ok=True)
full_path = os.path.join(output_dir, output_path)
# Ensure parent directory exists
parent_dir = os.path.dirname(full_path)
if parent_dir:
os.makedirs(parent_dir, exist_ok=True)
return full_path
def handle_api_analyze(args):
"""Handle the api-analyze command"""
project_path = args.project_path
# Validate project path exists
if not os.path.exists(project_path):
print(f"Error: Project path '{project_path}' not found", file=sys.stderr)
return 1
# Validate it's a directory
if not os.path.isdir(project_path):
print(f"Error: '{project_path}' is not a directory", file=sys.stderr)
return 1
try:
# Create analyzer
analyzer = APIAnalyzer(project_path)
# Perform analysis
endpoints = analyzer.analyze()
if not endpoints:
print("No public APIs found in the project")
return 0
# Create formatter
formatter = APIOutputFormatter()
# Display results
if args.summary:
# Show summary table only
formatter.print_summary_table(endpoints)
else:
# Show full analysis
formatter.print_api_analysis(endpoints, project_path)
# Export to markdown if requested
if args.export:
# Ensure output is saved in api-reports directory
output_file = ensure_output_directory(args.export, 'api-reports')
formatter.export_to_markdown(endpoints, project_path, output_file)
return 0
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
import traceback
traceback.print_exc()
return 1
def main():
parser = argparse.ArgumentParser(
description="Analyze Java code and generate Mockito mocks for testing",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Analyze a Java class
python main.py analyze UserService.java
# Generate test class with mocks
python main.py generate UserService.java --output UserServiceTest.java
# Quick mock setup only
python main.py generate UserService.java --quick-mocks
# Analyze with verbose output
python main.py analyze UserService.java --verbose
# Analyze project APIs and call sequences
python main.py api-analyze /path/to/project
# Export API analysis to markdown
python main.py api-analyze /path/to/project --export api-report.md
"""
)
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# Analyze command
analyze_parser = subparsers.add_parser(
'analyze',
help='Analyze Java code and show testing insights'
)
analyze_parser.add_argument('file', help='Path to the Java file')
analyze_parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Show detailed analysis'
)
# Generate command
generate_parser = subparsers.add_parser(
'generate',
help='Generate Mockito test class'
)
generate_parser.add_argument('file', help='Path to the Java file')
generate_parser.add_argument(
'--output', '-o',
help='Output file for generated test class'
)
generate_parser.add_argument(
'--quick-mocks',
action='store_true',
help='Generate quick mock setup only (not full test class)'
)
generate_parser.add_argument(
'--no-setup',
action='store_true',
help='Skip @Before setup method'
)
# API Analyze command
api_analyze_parser = subparsers.add_parser(
'api-analyze',
help='Analyze project APIs and their invocation sequences'
)
api_analyze_parser.add_argument(
'project_path',
help='Path to the project directory to analyze'
)
api_analyze_parser.add_argument(
'--export', '-e',
help='Export analysis to markdown file'
)
api_analyze_parser.add_argument(
'--summary',
action='store_true',
help='Show summary table only'
)
args = parser.parse_args()
if not args.command:
parser.print_help()
return 1
# Handle api-analyze command separately (works on directories)
if args.command == 'api-analyze':
return handle_api_analyze(args)
# Validate file exists (for analyze and generate commands)
if not os.path.exists(args.file):
print(f"Error: File '{args.file}' not found", file=sys.stderr)
return 1
# Validate it's a Java file
if not args.file.endswith('.java'):
print(f"Error: File must be a .java file", file=sys.stderr)
return 1
try:
# Parse the Java file
print(f"Parsing {args.file}...")
parser = JavaParser(args.file)
java_class = parser.parse()
if args.command == 'analyze':
# Analyze the code
analyzer = JavaAnalyzer(java_class)
analysis = analyzer.analyze()
# Display results
formatter = ConsoleFormatter()
formatter.print_analysis(analysis, java_class)
elif args.command == 'generate':
# Generate mocks
generator = MockitoGenerator(java_class)
if args.quick_mocks:
# Generate quick mock setup
mock_code = generator.generate_quick_mocks()
if args.output:
# Save in generated-tests directory
output_file = ensure_output_directory(args.output, 'generated-tests')
with open(output_file, 'w') as f:
f.write(mock_code)
print(f"✓ Quick mocks generated: {output_file}")
else:
print("\n" + "=" * 60)
print("Quick Mock Setup")
print("=" * 60)
print(mock_code)
print("=" * 60 + "\n")
else:
# Generate full test class
include_setup = not args.no_setup
test_code = generator.generate_test_class(include_setup=include_setup)
if args.output:
# Save in generated-tests directory
output_file = ensure_output_directory(args.output, 'generated-tests')
with open(output_file, 'w') as f:
f.write(test_code)
formatter = ConsoleFormatter()
formatter.print_generation_complete(output_file)
else:
print(test_code)
return 0
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
if getattr(args, 'verbose', False):
import traceback
traceback.print_exc()
return 1
if __name__ == '__main__':
sys.exit(main())