-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_javascript_optimization_flow.py
More file actions
554 lines (446 loc) · 19.1 KB
/
test_javascript_optimization_flow.py
File metadata and controls
554 lines (446 loc) · 19.1 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
"""End-to-end tests for JavaScript/TypeScript optimization flow.
These tests verify the full optimization pipeline including:
- Test generation (with mocked backend)
- Language parameter propagation
- Syntax validation with correct parser
- Running and parsing tests
This is the JavaScript equivalent of test_instrument_tests.py for Python.
"""
from unittest.mock import MagicMock, patch
import pytest
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.languages.base import Language
from codeflash.models.models import CodeString, FunctionParent
from codeflash.verification.verification_utils import TestConfig
def skip_if_js_not_supported():
"""Skip test if JavaScript/TypeScript languages are not supported."""
try:
from codeflash.languages import get_language_support
get_language_support(Language.JAVASCRIPT)
except Exception as e:
pytest.skip(f"JavaScript/TypeScript language support not available: {e}")
class TestLanguageParameterPropagation:
"""Tests verifying language parameter is correctly passed through all layers."""
def test_function_to_optimize_has_correct_language_for_typescript(self, tmp_path):
"""Verify FunctionToOptimize has language='typescript' for .ts files."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
ts_file = tmp_path / "utils.ts"
ts_file.write_text("""
export function add(a: number, b: number): number {
return a + b;
}
""")
functions = find_all_functions_in_file(ts_file)
assert ts_file in functions
assert len(functions[ts_file]) == 1
assert functions[ts_file][0].language == "typescript"
def test_function_to_optimize_has_correct_language_for_javascript(self, tmp_path):
"""Verify FunctionToOptimize has language='javascript' for .js files."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
js_file = tmp_path / "utils.js"
js_file.write_text("""
function add(a, b) {
return a + b;
}
module.exports = { add };
""")
functions = find_all_functions_in_file(js_file)
assert js_file in functions
assert len(functions[js_file]) == 1
assert functions[js_file][0].language == "javascript"
def test_code_context_preserves_language(self, tmp_path):
"""Verify language is preserved in code context extraction."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.languages import get_language_support
from codeflash.languages.javascript.function_optimizer import JavaScriptFunctionOptimizer
ts_file = tmp_path / "utils.ts"
ts_file.write_text("""
export function add(a: number, b: number): number {
return a + b;
}
""")
functions = find_all_functions_in_file(ts_file)
func = functions[ts_file][0]
ts_support = get_language_support(Language.TYPESCRIPT)
code_context = ts_support.extract_code_context(func, tmp_path, tmp_path)
context = JavaScriptFunctionOptimizer._build_optimization_context(
code_context, ts_file, "typescript", tmp_path
)
assert context.read_writable_code is not None
assert context.read_writable_code.language == "typescript"
class TestCodeStringSyntaxValidation:
"""Tests verifying CodeString validates with correct parser based on language."""
def test_typescript_code_valid_with_typescript_language(self):
"""TypeScript code should pass validation when language='typescript'."""
skip_if_js_not_supported()
ts_code = "const value = 4.9 as unknown as number;"
code_string = CodeString(code=ts_code, language="typescript")
assert code_string.code == ts_code
def test_typescript_code_invalid_with_javascript_language(self):
"""TypeScript code should FAIL validation when language='javascript'.
This is the exact bug that was in production - TypeScript code being
validated with JavaScript parser.
"""
skip_if_js_not_supported()
from pydantic import ValidationError
ts_code = "const value = 4.9 as unknown as number;"
with pytest.raises(ValidationError) as exc_info:
CodeString(code=ts_code, language="javascript")
assert "Invalid Javascript code" in str(exc_info.value)
def test_typescript_interface_valid_with_typescript_language(self):
"""TypeScript interface should pass validation when language='typescript'."""
skip_if_js_not_supported()
ts_code = "interface User { name: string; age: number; }"
code_string = CodeString(code=ts_code, language="typescript")
assert code_string.code == ts_code
def test_typescript_interface_invalid_with_javascript_language(self):
"""TypeScript interface should FAIL validation when language='javascript'."""
skip_if_js_not_supported()
from pydantic import ValidationError
ts_code = "interface User { name: string; age: number; }"
with pytest.raises(ValidationError) as exc_info:
CodeString(code=ts_code, language="javascript")
assert "Invalid Javascript code" in str(exc_info.value)
class TestBackendAPIResponseValidation:
"""Tests verifying backend API responses are validated with correct parser."""
def test_testgen_request_includes_correct_language(self, tmp_path):
"""Verify test generation request includes the correct language parameter."""
skip_if_js_not_supported()
from codeflash.api.aiservice import AiServiceClient
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.languages import current as lang_current
lang_current._current_language = Language.TYPESCRIPT
ts_file = tmp_path / "utils.ts"
ts_file.write_text("""
export function add(a: number, b: number): number {
return a + b;
}
""")
functions = find_all_functions_in_file(ts_file)
func = functions[ts_file][0]
# Verify function has correct language
assert func.language == "typescript"
# Mock the AI service request
ai_client = AiServiceClient()
with patch.object(ai_client, "make_ai_service_request") as mock_request:
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"generated_tests": "// test code",
"instrumented_behavior_tests": "// behavior code",
"instrumented_perf_tests": "// perf code",
}
mock_request.return_value = mock_response
# Call generate_regression_tests with correct parameters
ai_client.generate_regression_tests(
source_code_being_tested="export function add(a: number, b: number): number { return a + b; }",
function_to_optimize=func,
helper_function_names=[],
module_path=ts_file,
test_module_path=tmp_path / "tests" / "utils.test.ts",
test_framework="vitest",
test_timeout=30,
trace_id="test-trace-id",
test_index=0,
language=func.language, # This is the key - language should be "typescript"
)
# Verify the request was made with correct language
assert mock_request.called, "API request should have been made"
call_args = mock_request.call_args
payload = call_args[1].get("payload", call_args[0][1] if len(call_args[0]) > 1 else {})
assert payload.get("language") == "typescript", \
f"Expected language='typescript', got language='{payload.get('language')}'"
class TestFunctionOptimizerForJavaScript:
"""Tests for FunctionOptimizer with JavaScript/TypeScript functions.
This is the JavaScript equivalent of test_instrument_tests.py tests.
"""
@pytest.fixture
def js_project(self, tmp_path):
"""Create a minimal JavaScript project for testing."""
project = tmp_path / "js_project"
project.mkdir()
# Create source file
src_file = project / "utils.js"
src_file.write_text("""
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
module.exports = { fibonacci };
""")
# Create test file
tests_dir = project / "tests"
tests_dir.mkdir()
test_file = tests_dir / "utils.test.js"
test_file.write_text("""
const { fibonacci } = require('../utils');
describe('fibonacci', () => {
test('returns 0 for n=0', () => {
expect(fibonacci(0)).toBe(0);
});
test('returns 1 for n=1', () => {
expect(fibonacci(1)).toBe(1);
});
test('returns 5 for n=5', () => {
expect(fibonacci(5)).toBe(5);
});
});
""")
# Create package.json
package_json = project / "package.json"
package_json.write_text("""
{
"name": "test-project",
"devDependencies": {
"jest": "^29.0.0"
}
}
""")
return project
@pytest.fixture
def ts_project(self, tmp_path):
"""Create a minimal TypeScript project for testing."""
project = tmp_path / "ts_project"
project.mkdir()
# Create source file
src_file = project / "utils.ts"
src_file.write_text("""
export function fibonacci(n: number): number {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
""")
# Create test file
tests_dir = project / "tests"
tests_dir.mkdir()
test_file = tests_dir / "utils.test.ts"
test_file.write_text("""
import { fibonacci } from '../utils';
describe('fibonacci', () => {
test('returns 0 for n=0', () => {
expect(fibonacci(0)).toBe(0);
});
test('returns 1 for n=1', () => {
expect(fibonacci(1)).toBe(1);
});
});
""")
# Create package.json
package_json = project / "package.json"
package_json.write_text("""
{
"name": "test-project",
"devDependencies": {
"vitest": "^1.0.0"
}
}
""")
return project
def test_function_optimizer_instantiation_javascript(self, js_project):
"""Test FunctionOptimizer can be instantiated for JavaScript."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.optimization.function_optimizer import FunctionOptimizer
src_file = js_project / "utils.js"
functions = find_all_functions_in_file(src_file)
func = functions[src_file][0]
func_to_optimize = FunctionToOptimize(
function_name=func.function_name,
file_path=func.file_path,
parents=[FunctionParent(name=p.name, type=p.type) for p in func.parents],
starting_line=func.starting_line,
ending_line=func.ending_line,
language=func.language,
)
test_config = TestConfig(
tests_root=js_project / "tests",
tests_project_rootdir=js_project,
project_root_path=js_project,
pytest_cmd="jest",
)
optimizer = FunctionOptimizer(
function_to_optimize=func_to_optimize,
test_cfg=test_config,
aiservice_client=MagicMock(),
)
assert optimizer is not None
assert optimizer.function_to_optimize.language == "javascript"
def test_function_optimizer_instantiation_typescript(self, ts_project):
"""Test FunctionOptimizer can be instantiated for TypeScript."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.optimization.function_optimizer import FunctionOptimizer
src_file = ts_project / "utils.ts"
functions = find_all_functions_in_file(src_file)
func = functions[src_file][0]
func_to_optimize = FunctionToOptimize(
function_name=func.function_name,
file_path=func.file_path,
parents=[FunctionParent(name=p.name, type=p.type) for p in func.parents],
starting_line=func.starting_line,
ending_line=func.ending_line,
language=func.language,
)
test_config = TestConfig(
tests_root=ts_project / "tests",
tests_project_rootdir=ts_project,
project_root_path=ts_project,
pytest_cmd="vitest",
)
optimizer = FunctionOptimizer(
function_to_optimize=func_to_optimize,
test_cfg=test_config,
aiservice_client=MagicMock(),
)
assert optimizer is not None
assert optimizer.function_to_optimize.language == "typescript"
def test_get_code_optimization_context_javascript(self, js_project):
"""Test get_code_optimization_context for JavaScript."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.languages.javascript.function_optimizer import JavaScriptFunctionOptimizer
src_file = js_project / "utils.js"
functions = find_all_functions_in_file(src_file)
func = functions[src_file][0]
func_to_optimize = FunctionToOptimize(
function_name=func.function_name,
file_path=func.file_path,
parents=[FunctionParent(name=p.name, type=p.type) for p in func.parents],
starting_line=func.starting_line,
ending_line=func.ending_line,
language=func.language,
)
test_config = TestConfig(
tests_root=js_project / "tests",
tests_project_rootdir=js_project,
project_root_path=js_project,
pytest_cmd="jest",
)
optimizer = JavaScriptFunctionOptimizer(
function_to_optimize=func_to_optimize,
test_cfg=test_config,
aiservice_client=MagicMock(),
)
result = optimizer.get_code_optimization_context()
context = result.unwrap()
assert context is not None
assert context.read_writable_code is not None
assert context.read_writable_code.language == "javascript"
def test_get_code_optimization_context_typescript(self, ts_project):
"""Test get_code_optimization_context for TypeScript."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.languages.javascript.function_optimizer import JavaScriptFunctionOptimizer
src_file = ts_project / "utils.ts"
functions = find_all_functions_in_file(src_file)
func = functions[src_file][0]
func_to_optimize = FunctionToOptimize(
function_name=func.function_name,
file_path=func.file_path,
parents=[FunctionParent(name=p.name, type=p.type) for p in func.parents],
starting_line=func.starting_line,
ending_line=func.ending_line,
language=func.language,
)
test_config = TestConfig(
tests_root=ts_project / "tests",
tests_project_rootdir=ts_project,
project_root_path=ts_project,
pytest_cmd="vitest",
)
optimizer = JavaScriptFunctionOptimizer(
function_to_optimize=func_to_optimize,
test_cfg=test_config,
aiservice_client=MagicMock(),
)
result = optimizer.get_code_optimization_context()
context = result.unwrap()
assert context is not None
assert context.read_writable_code is not None
assert context.read_writable_code.language == "typescript"
class TestHelperFunctionLanguageAttribute:
"""Tests for helper function language attribute (import_resolver.py fix)."""
def test_helper_functions_have_correct_language_javascript(self, tmp_path):
"""Verify helper functions have language='javascript' for .js files."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.languages.javascript.function_optimizer import JavaScriptFunctionOptimizer
# Create a file with helper functions
src_file = tmp_path / "main.js"
src_file.write_text("""
function helper() {
return 42;
}
function main() {
return helper() * 2;
}
module.exports = { main };
""")
functions = find_all_functions_in_file(src_file)
main_func = next(f for f in functions[src_file] if f.function_name == "main")
func_to_optimize = FunctionToOptimize(
function_name=main_func.function_name,
file_path=main_func.file_path,
parents=[],
starting_line=main_func.starting_line,
ending_line=main_func.ending_line,
language=main_func.language,
)
test_config = TestConfig(
tests_root=tmp_path,
tests_project_rootdir=tmp_path,
project_root_path=tmp_path,
pytest_cmd="jest",
)
optimizer = JavaScriptFunctionOptimizer(
function_to_optimize=func_to_optimize,
test_cfg=test_config,
aiservice_client=MagicMock(),
)
result = optimizer.get_code_optimization_context()
context = result.unwrap()
# Verify main function has correct language
assert context.read_writable_code.language == "javascript"
def test_helper_functions_have_correct_language_typescript(self, tmp_path):
"""Verify helper functions have language='typescript' for .ts files."""
skip_if_js_not_supported()
from codeflash.discovery.functions_to_optimize import find_all_functions_in_file
from codeflash.languages.javascript.function_optimizer import JavaScriptFunctionOptimizer
# Create a file with helper functions
src_file = tmp_path / "main.ts"
src_file.write_text("""
function helper(): number {
return 42;
}
export function main(): number {
return helper() * 2;
}
""")
functions = find_all_functions_in_file(src_file)
main_func = next(f for f in functions[src_file] if f.function_name == "main")
func_to_optimize = FunctionToOptimize(
function_name=main_func.function_name,
file_path=main_func.file_path,
parents=[],
starting_line=main_func.starting_line,
ending_line=main_func.ending_line,
language=main_func.language,
)
test_config = TestConfig(
tests_root=tmp_path,
tests_project_rootdir=tmp_path,
project_root_path=tmp_path,
pytest_cmd="vitest",
)
optimizer = JavaScriptFunctionOptimizer(
function_to_optimize=func_to_optimize,
test_cfg=test_config,
aiservice_client=MagicMock(),
)
result = optimizer.get_code_optimization_context()
context = result.unwrap()
# Verify main function has correct language
assert context.read_writable_code.language == "typescript"