-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtest_javascript_support.py
More file actions
1725 lines (1426 loc) · 53 KB
/
Copy pathtest_javascript_support.py
File metadata and controls
1725 lines (1426 loc) · 53 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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Extensive tests for the JavaScript language support implementation.
These tests verify that JavaScriptSupport correctly discovers functions,
replaces code, and integrates with the codeflash language abstraction.
"""
import tempfile
from pathlib import Path
import pytest
from codeflash.languages.base import FunctionFilterCriteria, FunctionInfo, Language, ParentInfo
from codeflash.languages.javascript.support import JavaScriptSupport
@pytest.fixture
def js_support():
"""Create a JavaScriptSupport instance."""
return JavaScriptSupport()
class TestJavaScriptSupportProperties:
"""Tests for JavaScriptSupport properties."""
def test_language(self, js_support):
"""Test language property."""
assert js_support.language == Language.JAVASCRIPT
def test_file_extensions(self, js_support):
"""Test file_extensions property."""
extensions = js_support.file_extensions
assert ".js" in extensions
assert ".jsx" in extensions
assert ".mjs" in extensions
assert ".cjs" in extensions
def test_test_framework(self, js_support):
"""Test test_framework property."""
assert js_support.test_framework == "jest"
class TestDiscoverFunctions:
"""Tests for discover_functions method."""
def test_discover_simple_function(self, js_support):
"""Test discovering a simple function declaration."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export function add(a, b) {
return a + b;
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 1
assert functions[0].function_name == "add"
assert functions[0].language == Language.JAVASCRIPT
def test_discover_multiple_functions(self, js_support):
"""Test discovering multiple functions."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export function multiply(a, b) {
return a * b;
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 3
names = {func.function_name for func in functions}
assert names == {"add", "subtract", "multiply"}
def test_discover_arrow_function(self, js_support):
"""Test discovering arrow functions assigned to variables."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export const add = (a, b) => {
return a + b;
};
export const multiply = (x, y) => x * y;
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 2
names = {func.function_name for func in functions}
assert names == {"add", "multiply"}
def test_discover_function_without_return_excluded(self, js_support):
"""Test that functions without return are excluded by default."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export function withReturn() {
return 1;
}
export function withoutReturn() {
console.log("hello");
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
# Only the function with return should be discovered
assert len(functions) == 1
assert functions[0].function_name == "withReturn"
def test_discover_class_methods(self, js_support):
"""Test discovering class methods."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export class Calculator {
add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 2
for func in functions:
assert func.is_method is True
assert func.class_name == "Calculator"
def test_discover_async_functions(self, js_support):
"""Test discovering async functions."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export async function fetchData(url) {
return await fetch(url);
}
export function syncFunction() {
return 1;
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 2
async_func = next(f for f in functions if f.function_name == "fetchData")
sync_func = next(f for f in functions if f.function_name == "syncFunction")
assert async_func.is_async is True
assert sync_func.is_async is False
def test_discover_with_filter_exclude_async(self, js_support):
"""Test filtering out async functions."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export async function asyncFunc() {
return 1;
}
export function syncFunc() {
return 2;
}
""")
f.flush()
criteria = FunctionFilterCriteria(include_async=False)
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name), criteria)
assert len(functions) == 1
assert functions[0].function_name == "syncFunc"
def test_discover_with_filter_exclude_methods(self, js_support):
"""Test filtering out class methods."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export function standalone() {
return 1;
}
export class MyClass {
method() {
return 2;
}
}
""")
f.flush()
criteria = FunctionFilterCriteria(include_methods=False)
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name), criteria)
assert len(functions) == 1
assert functions[0].function_name == "standalone"
def test_discover_line_numbers(self, js_support):
"""Test that line numbers are correctly captured."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export function func1() {
return 1;
}
export function func2() {
const x = 1;
const y = 2;
return x + y;
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
func1 = next(f for f in functions if f.function_name == "func1")
func2 = next(f for f in functions if f.function_name == "func2")
assert func1.starting_line == 1
assert func1.ending_line == 3
assert func2.starting_line == 5
assert func2.ending_line == 9
def test_discover_generator_function(self, js_support):
"""Test discovering generator functions."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export function* numberGenerator() {
yield 1;
yield 2;
return 3;
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 1
assert functions[0].function_name == "numberGenerator"
def test_discover_invalid_file_returns_empty(self, js_support):
"""Test that invalid JavaScript file returns empty list."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("this is not valid javascript {{{{")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
# Tree-sitter is lenient, so it may still parse partial code
# The important thing is it doesn't crash
assert isinstance(functions, list)
def test_discover_nonexistent_file_returns_empty(self, js_support):
"""Test that nonexistent file returns empty list."""
functions = js_support.discover_functions("", Path("/nonexistent/file.js"))
assert functions == []
def test_discover_function_expression(self, js_support):
"""Test discovering function expressions."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export const add = function(a, b) {
return a + b;
};
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
assert len(functions) == 1
assert functions[0].function_name == "add"
def test_discover_immediately_invoked_function_excluded(self, js_support):
"""Test that IIFEs without names are excluded when require_name is True."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
(function() {
return 1;
})();
export function named() {
return 2;
}
""")
f.flush()
functions = js_support.discover_functions(Path(f.name).read_text(encoding="utf-8"), Path(f.name))
# Only the named function should be discovered
assert len(functions) == 1
assert functions[0].function_name == "named"
class TestReplaceFunction:
"""Tests for replace_function method."""
def test_replace_simple_function(self, js_support):
"""Test replacing a simple function."""
source = """function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
"""
func = FunctionInfo(function_name="add", file_path=Path("/test.js"), starting_line=1, ending_line=3)
new_code = """function add(a, b) {
// Optimized
return (a + b) | 0;
}
"""
result = js_support.replace_function(source, func, new_code)
assert "// Optimized" in result
assert "return (a + b) | 0" in result
assert "function multiply" in result
def test_replace_preserves_surrounding_code(self, js_support):
"""Test that replacement preserves code before and after."""
source = """// Header comment
import { something } from './module';
function target() {
return 1;
}
function other() {
return 2;
}
// Footer
"""
func = FunctionInfo(function_name="target", file_path=Path("/test.js"), starting_line=4, ending_line=6)
new_code = """function target() {
return 42;
}
"""
result = js_support.replace_function(source, func, new_code)
assert "// Header comment" in result
assert "import { something }" in result
assert "return 42" in result
assert "function other" in result
assert "// Footer" in result
def test_replace_with_indentation_adjustment(self, js_support):
"""Test that indentation is adjusted correctly."""
source = """class Calculator {
add(a, b) {
return a + b;
}
}
"""
func = FunctionInfo(
function_name="add",
file_path=Path("/test.js"),
starting_line=2,
ending_line=4,
parents=[ParentInfo(name="Calculator", type="ClassDef")],
)
# New code has no indentation
new_code = """add(a, b) {
return (a + b) | 0;
}
"""
result = js_support.replace_function(source, func, new_code)
# Check that indentation was added
lines = result.splitlines()
method_line = next(l for l in lines if "add(a, b)" in l)
assert method_line.startswith(" ") # 4 spaces
def test_replace_arrow_function(self, js_support):
"""Test replacing an arrow function."""
source = """const add = (a, b) => {
return a + b;
};
const multiply = (x, y) => x * y;
"""
func = FunctionInfo(function_name="add", file_path=Path("/test.js"), starting_line=1, ending_line=3)
new_code = """const add = (a, b) => {
return (a + b) | 0;
};
"""
result = js_support.replace_function(source, func, new_code)
assert "(a + b) | 0" in result
assert "multiply" in result
class TestValidateSyntax:
"""Tests for validate_syntax method."""
def test_valid_syntax(self, js_support):
"""Test that valid JavaScript syntax passes."""
valid_code = """
function add(a, b) {
return a + b;
}
class Calculator {
multiply(x, y) {
return x * y;
}
}
"""
assert js_support.validate_syntax(valid_code) is True
def test_invalid_syntax(self, js_support):
"""Test that invalid JavaScript syntax fails."""
invalid_code = """
function add(a, b {
return a + b;
}
"""
assert js_support.validate_syntax(invalid_code) is False
def test_empty_string_valid(self, js_support):
"""Test that empty string is valid syntax."""
assert js_support.validate_syntax("") is True
def test_syntax_error_types(self, js_support):
"""Test various syntax error types."""
# Unclosed bracket
assert js_support.validate_syntax("const x = [1, 2, 3") is False
# Missing closing brace
assert js_support.validate_syntax("function foo() {") is False
class TestNormalizeCode:
"""Tests for normalize_code method using tree-sitter normalizer."""
def test_removes_comments(self, js_support):
"""Test that comments are absent from normalized output."""
code = """
function add(a, b) {
// Add two numbers
return a + b;
}
"""
normalized = js_support.normalize_code(code)
assert "// Add two numbers" not in normalized
assert "Add two numbers" not in normalized
def test_same_logic_different_vars_are_equal(self, js_support):
"""Test that two functions with same logic but different variable names normalize identically."""
code1 = """
function process(items) {
const result = [];
for (const item of items) {
result.push(item * 2);
}
return result;
}
"""
code2 = """
function process(items) {
const output = [];
for (const val of items) {
output.push(val * 2);
}
return output;
}
"""
assert js_support.normalize_code(code1) == js_support.normalize_code(code2)
def test_different_logic_not_equal(self, js_support):
"""Test that two functions with different logic produce different normalized forms."""
code1 = """
function compute(x) {
return x + 1;
}
"""
code2 = """
function compute(x) {
return x * 2;
}
"""
assert js_support.normalize_code(code1) != js_support.normalize_code(code2)
class TestExtractCodeContext:
"""Tests for extract_code_context method."""
def test_extract_simple_function(self, js_support):
"""Test extracting context for a simple function."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export function add(a, b) {
return a + b;
}
""")
f.flush()
file_path = Path(f.name)
func = FunctionInfo(function_name="add", file_path=file_path, starting_line=1, ending_line=3)
context = js_support.extract_code_context(func, file_path.parent, file_path.parent)
assert "function add" in context.target_code
assert "return a + b" in context.target_code
assert context.target_file == file_path
assert context.language == Language.JAVASCRIPT
def test_extract_with_helper(self, js_support):
"""Test extracting context with helper functions."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export function helper(x) {
return x * 2;
}
export function main(a) {
return helper(a) + 1;
}
""")
f.flush()
file_path = Path(f.name)
# First discover functions to get accurate line numbers
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
main_func = next(f for f in functions if f.function_name == "main")
context = js_support.extract_code_context(main_func, file_path.parent, file_path.parent)
assert "function main" in context.target_code
# Helper should be found
assert len(context.helper_functions) >= 0 # May or may not find helper
class TestIntegration:
"""Integration tests for JavaScriptSupport."""
def test_discover_and_replace_workflow(self, js_support):
"""Test full discover -> replace workflow."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
original_code = """export function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
"""
f.write(original_code)
f.flush()
file_path = Path(f.name)
# Discover
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
assert len(functions) == 1
func = functions[0]
assert func.function_name == "fibonacci"
# Replace
optimized_code = """export function fibonacci(n) {
// Memoized version
const memo = {0: 0, 1: 1};
for (let i = 2; i <= n; i++) {
memo[i] = memo[i-1] + memo[i-2];
}
return memo[n];
}
"""
result = js_support.replace_function(original_code, func, optimized_code)
# Validate
assert js_support.validate_syntax(result) is True
assert "Memoized version" in result
assert "memo[n]" in result
def test_multiple_classes_and_functions(self, js_support):
"""Test discovering and working with complex file."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""
export class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
}
export class StringUtils {
reverse(s) {
return s.split('').reverse().join('');
}
}
export function standalone() {
return 42;
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
# Should find 4 functions
assert len(functions) == 4
# Check class methods
calc_methods = [f for f in functions if f.class_name == "Calculator"]
assert len(calc_methods) == 2
string_methods = [f for f in functions if f.class_name == "StringUtils"]
assert len(string_methods) == 1
standalone_funcs = [f for f in functions if f.class_name is None]
assert len(standalone_funcs) == 1
def test_jsx_file(self, js_support):
"""Test discovering functions in JSX files."""
with tempfile.NamedTemporaryFile(suffix=".jsx", mode="w", delete=False) as f:
f.write("""
import React from 'react';
export function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>;
}
export const Card = ({ title, content }) => {
return (
<div className="card">
<h2>{title}</h2>
<p>{content}</p>
</div>
);
};
export default Button;
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
# Should find both components
names = {f.function_name for f in functions}
assert "Button" in names
assert "Card" in names
class TestJestTestDiscovery:
"""Tests for Jest test discovery."""
def test_find_jest_tests(self, js_support):
"""Test finding Jest test functions."""
with tempfile.NamedTemporaryFile(suffix=".test.js", mode="w", delete=False) as f:
f.write("""
import { add } from './math';
describe('Math functions', () => {
test('add returns sum', () => {
expect(add(1, 2)).toBe(3);
});
it('handles negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});
});
""")
f.flush()
file_path = Path(f.name)
source = file_path.read_text(encoding="utf-8")
from codeflash.languages.javascript.treesitter import get_analyzer_for_file
analyzer = get_analyzer_for_file(file_path)
test_names = js_support._find_jest_tests(source, analyzer)
assert "Math functions" in test_names
assert "add returns sum" in test_names
assert "handles negative numbers" in test_names
class TestClassMethodExtraction:
"""Tests for class method extraction and code context.
These tests use full string equality to verify exact extraction output.
"""
def test_extract_class_method_wraps_in_class(self, js_support):
"""Test that extracting a class method wraps it in a class definition."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export class Calculator {
add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
""")
f.flush()
file_path = Path(f.name)
# Discover the method
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
add_method = next(f for f in functions if f.function_name == "add")
# Extract code context
context = js_support.extract_code_context(add_method, file_path.parent, file_path.parent)
# Full string equality check for exact extraction output
# Note: export keyword is not included in extracted class wrapper
expected_code = """class Calculator {
add(a, b) {
return a + b;
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
def test_extract_class_method_with_jsdoc(self, js_support):
"""Test extracting a class method with JSDoc comments."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""/**
* A simple calculator class.
*/
export class Calculator {
/**
* Adds two numbers.
* @param {number} a - First number
* @param {number} b - Second number
* @returns {number} The sum
*/
add(a, b) {
return a + b;
}
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
add_method = next(f for f in functions if f.function_name == "add")
context = js_support.extract_code_context(add_method, file_path.parent, file_path.parent)
# Full string equality check - includes class JSDoc, class definition, method JSDoc, and method
# Note: export keyword is not included in extracted class wrapper
# Note: Class-level JSDoc is not included when extracting a method
expected_code = """class Calculator {
/**
* Adds two numbers.
* @param {number} a - First number
* @param {number} b - Second number
* @returns {number} The sum
*/
add(a, b) {
return a + b;
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
def test_extract_class_method_syntax_valid(self, js_support):
"""Test that extracted class method code is always syntactically valid."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export class FibonacciCalculator {
fibonacci(n) {
if (n <= 1) {
return n;
}
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
fib_method = next(f for f in functions if f.function_name == "fibonacci")
context = js_support.extract_code_context(fib_method, file_path.parent, file_path.parent)
# Full string equality check
# Note: export keyword is not included in extracted class wrapper
expected_code = """class FibonacciCalculator {
fibonacci(n) {
if (n <= 1) {
return n;
}
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
def test_extract_nested_class_method(self, js_support):
"""Test extracting a method from a nested class structure."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export class Outer {
createInner() {
return class Inner {
getValue() {
return 42;
}
};
}
add(a, b) {
return a + b;
}
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
add_method = next((f for f in functions if f.function_name == "add"), None)
if add_method:
context = js_support.extract_code_context(add_method, file_path.parent, file_path.parent)
# Full string equality check
# Note: export keyword is not included in extracted class wrapper
expected_code = """class Outer {
add(a, b) {
return a + b;
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
def test_extract_async_class_method(self, js_support):
"""Test extracting an async class method."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export class ApiClient {
async fetchData(url) {
const response = await fetch(url);
return response.json();
}
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
fetch_method = next(f for f in functions if f.function_name == "fetchData")
context = js_support.extract_code_context(fetch_method, file_path.parent, file_path.parent)
# Full string equality check
# Note: export keyword is not included in extracted class wrapper
expected_code = """class ApiClient {
async fetchData(url) {
const response = await fetch(url);
return response.json();
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
def test_extract_static_class_method(self, js_support):
"""Test extracting a static class method."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export class MathUtils {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
add_method = next((f for f in functions if f.function_name == "add"), None)
if add_method:
context = js_support.extract_code_context(add_method, file_path.parent, file_path.parent)
# Full string equality check
# Note: export keyword is not included in extracted class wrapper
expected_code = """class MathUtils {
static add(a, b) {
return a + b;
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
def test_extract_class_method_without_class_jsdoc(self, js_support):
"""Test extracting a method from a class without JSDoc."""
with tempfile.NamedTemporaryFile(suffix=".js", mode="w", delete=False) as f:
f.write("""export class SimpleClass {
simpleMethod() {
return "hello";
}
}
""")
f.flush()
file_path = Path(f.name)
functions = js_support.discover_functions(file_path.read_text(encoding="utf-8"), file_path)
method = next(f for f in functions if f.function_name == "simpleMethod")
context = js_support.extract_code_context(method, file_path.parent, file_path.parent)
# Full string equality check
# Note: export keyword is not included in extracted class wrapper
expected_code = """class SimpleClass {
simpleMethod() {
return "hello";
}
}
"""
assert context.target_code == expected_code, f"Expected:\n{expected_code}\nGot:\n{context.target_code}"
assert js_support.validate_syntax(context.target_code) is True
class TestClassMethodReplacement:
"""Tests for replacing class methods."""
def test_replace_class_method_preserves_class_structure(self, js_support):
"""Test that replacing a class method preserves the class structure."""
source = """class Calculator {
add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
"""
func = FunctionInfo(
function_name="add",
file_path=Path("/test.js"),
starting_line=2,
ending_line=4,
parents=[ParentInfo(name="Calculator", type="ClassDef")],
is_method=True,
)
new_code = """ add(a, b) {
// Optimized bitwise addition
return (a + b) | 0;
}
"""
result = js_support.replace_function(source, func, new_code)
# Check class structure is preserved
assert "class Calculator" in result
assert "multiply(a, b)" in result
assert "return a * b" in result
# Check new code is inserted
assert "Optimized bitwise addition" in result
assert "(a + b) | 0" in result
# Check result is valid JavaScript
assert js_support.validate_syntax(result) is True
def test_replace_class_method_with_jsdoc(self, js_support):
"""Test replacing a class method that has JSDoc.
When new_code includes a JSDoc, it should replace the original JSDoc.
"""
source = """class Calculator {
/**
* Adds two numbers.
*/
add(a, b) {
return a + b;
}
}
"""
func = FunctionInfo(
function_name="add",
file_path=Path("/test.js"),
starting_line=5, # Method starts here
ending_line=7,
doc_start_line=2, # JSDoc starts here
parents=[ParentInfo(name="Calculator", type="ClassDef")],