-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_code_context_extraction.py
More file actions
2020 lines (1686 loc) · 60 KB
/
test_code_context_extraction.py
File metadata and controls
2020 lines (1686 loc) · 60 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
"""Tests for JavaScript/TypeScript code context extraction.
This module tests the extract_code_context method and related functionality
for JavaScript and TypeScript, mirroring the Python tests in test_code_context_extractor.py.
The tests cover:
- Simple functions and their dependencies
- Class methods with helpers and sibling method calls
- Helper functions in the same file
- Helper functions from imported files (cross-file)
- Global variables and constants
- Type definitions (TypeScript)
- JSDoc comments
- Constructor and fields context
- Nested dependencies (helper of helper)
- Circular dependencies
All assertions use strict string equality to verify exact extraction output.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.languages.base import Language
from codeflash.languages.javascript.support import JavaScriptSupport, TypeScriptSupport
from codeflash.languages.javascript.function_optimizer import JavaScriptFunctionOptimizer
from codeflash.verification.verification_utils import TestConfig
@pytest.fixture
def js_support():
"""Create a JavaScriptSupport instance."""
return JavaScriptSupport()
@pytest.fixture
def ts_support():
"""Create a TypeScriptSupport instance."""
return TypeScriptSupport()
@pytest.fixture
def temp_project(tmp_path):
"""Create a temporary project directory structure."""
project_root = tmp_path / "project"
project_root.mkdir()
return project_root
class TestSimpleFunctionContext:
"""Tests for simple function code context extraction with strict assertions."""
def test_simple_function_no_dependencies(self, js_support, temp_project):
"""Test extracting context for a simple standalone function without any dependencies."""
code = """\
export function add(a, b) {
return a + b;
}
"""
file_path = temp_project / "math.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
assert len(functions) == 1
func = functions[0]
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export function add(a, b) {
return a + b;
}
"""
assert context.target_code == expected_target_code
assert context.language == Language.JAVASCRIPT
assert context.target_file == file_path
assert context.helper_functions == []
assert context.read_only_context == ""
assert context.imports == []
def test_arrow_function_with_implicit_return(self, js_support, temp_project):
"""Test extracting an arrow function with implicit return."""
code = """\
export const multiply = (a, b) => a * b;
"""
file_path = temp_project / "math.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
assert len(functions) == 1
func = functions[0]
assert func.function_name == "multiply"
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export const multiply = (a, b) => a * b;
"""
assert context.target_code == expected_target_code
assert context.helper_functions == []
assert context.read_only_context == ""
class TestJSDocExtraction:
"""Tests for JSDoc comment extraction with complex documentation patterns."""
def test_function_with_simple_jsdoc(self, js_support, temp_project):
"""Test extracting function with simple JSDoc - exact string match."""
code = """\
/**
* Adds two numbers together.
* @param {number} a - First number
* @param {number} b - Second number
* @returns {number} The sum
*/
export function add(a, b) {
return a + b;
}
"""
file_path = temp_project / "math.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
func = functions[0]
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export function add(a, b) {
return a + b;
}
"""
assert context.target_code == expected_target_code
assert context.helper_functions == []
def test_function_with_complex_jsdoc_types(self, js_support, temp_project):
"""Test JSDoc with complex type annotations including generics, unions, and callbacks."""
code = """\
/**
* Processes an array of items with a callback function.
*
* This function iterates over each item and applies the transformation.
*
* @template T - The type of items in the input array
* @template U - The type of items in the output array
* @param {Array<T>} items - The input array to process
* @param {function(T, number): U} callback - Transformation function
* @param {Object} [options] - Optional configuration
* @param {boolean} [options.parallel=false] - Whether to process in parallel
* @param {number} [options.chunkSize=100] - Size of processing chunks
* @returns {Promise<Array<U>>} The transformed array
* @throws {TypeError} If items is not an array
* @example
* const doubled = await processItems([1, 2, 3], x => x * 2);
* // returns [2, 4, 6]
*/
export async function processItems(items, callback, options = {}) {
const { parallel = false, chunkSize = 100 } = options;
if (!Array.isArray(items)) {
throw new TypeError('items must be an array');
}
const results = [];
for (let i = 0; i < items.length; i++) {
results.push(callback(items[i], i));
}
return results;
}
"""
file_path = temp_project / "processor.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
func = functions[0]
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export async function processItems(items, callback, options = {}) {
const { parallel = false, chunkSize = 100 } = options;
if (!Array.isArray(items)) {
throw new TypeError('items must be an array');
}
const results = [];
for (let i = 0; i < items.length; i++) {
results.push(callback(items[i], i));
}
return results;
}
"""
assert context.target_code == expected_target_code
def test_class_with_jsdoc_on_class_and_methods(self, js_support, temp_project):
"""Test class where both the class and method have JSDoc comments."""
code = """\
/**
* A cache implementation with TTL support.
*
* @class CacheManager
* @description Provides in-memory caching with automatic expiration.
*/
export class CacheManager {
/**
* Creates a new cache manager.
* @param {number} defaultTTL - Default time-to-live in milliseconds
*/
constructor(defaultTTL = 60000) {
this.cache = new Map();
this.defaultTTL = defaultTTL;
}
/**
* Retrieves a value from cache or computes it.
*
* If the key exists and hasn't expired, returns the cached value.
* Otherwise, calls the factory function and caches the result.
*
* @param {string} key - The cache key
* @param {function(): T} factory - Factory function to compute value
* @param {number} [ttl] - Optional TTL override
* @returns {T} The cached or computed value
* @template T
*/
getOrCompute(key, factory, ttl) {
const existing = this.cache.get(key);
if (existing && existing.expiry > Date.now()) {
return existing.value;
}
const value = factory();
const expiry = Date.now() + (ttl || this.defaultTTL);
this.cache.set(key, { value, expiry });
return value;
}
}
"""
file_path = temp_project / "cache.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
get_or_compute = next(f for f in functions if f.function_name == "getOrCompute")
context = js_support.extract_code_context(get_or_compute, temp_project, temp_project)
expected_target_code = """\
class CacheManager {
/**
* Creates a new cache manager.
* @param {number} defaultTTL - Default time-to-live in milliseconds
*/
constructor(defaultTTL = 60000) {
this.cache = new Map();
this.defaultTTL = defaultTTL;
}
/**
* Retrieves a value from cache or computes it.
*
* If the key exists and hasn't expired, returns the cached value.
* Otherwise, calls the factory function and caches the result.
*
* @param {string} key - The cache key
* @param {function(): T} factory - Factory function to compute value
* @param {number} [ttl] - Optional TTL override
* @returns {T} The cached or computed value
* @template T
*/
getOrCompute(key, factory, ttl) {
const existing = this.cache.get(key);
if (existing && existing.expiry > Date.now()) {
return existing.value;
}
const value = factory();
const expiry = Date.now() + (ttl || this.defaultTTL);
this.cache.set(key, { value, expiry });
return value;
}
}
"""
assert context.target_code == expected_target_code
assert js_support.validate_syntax(context.target_code) is True
def test_jsdoc_with_typedef_and_callback(self, js_support, temp_project):
"""Test JSDoc with @typedef and @callback definitions referenced in function."""
code = """\
/**
* @typedef {Object} ValidationResult
* @property {boolean} valid - Whether validation passed
* @property {string[]} errors - List of error messages
* @property {Object.<string, string>} fieldErrors - Field-specific errors
*/
/**
* @callback ValidatorFunction
* @param {*} value - The value to validate
* @param {Object} context - Validation context
* @returns {ValidationResult}
*/
const EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
/**
* Validates user input data.
* @param {Object} data - The data to validate
* @param {ValidatorFunction[]} validators - Array of validator functions
* @returns {ValidationResult} Combined validation result
*/
export function validateUserData(data, validators) {
const errors = [];
const fieldErrors = {};
for (const validator of validators) {
const result = validator(data, { strict: true });
if (!result.valid) {
errors.push(...result.errors);
Object.assign(fieldErrors, result.fieldErrors);
}
}
if (data.email && !EMAIL_REGEX.test(data.email)) {
errors.push('Invalid email format');
fieldErrors.email = 'Invalid email format';
}
return {
valid: errors.length === 0,
errors,
fieldErrors
};
}
"""
file_path = temp_project / "validator.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
func = next(f for f in functions if f.function_name == "validateUserData")
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export function validateUserData(data, validators) {
const errors = [];
const fieldErrors = {};
for (const validator of validators) {
const result = validator(data, { strict: true });
if (!result.valid) {
errors.push(...result.errors);
Object.assign(fieldErrors, result.fieldErrors);
}
}
if (data.email && !EMAIL_REGEX.test(data.email)) {
errors.push('Invalid email format');
fieldErrors.email = 'Invalid email format';
}
return {
valid: errors.length === 0,
errors,
fieldErrors
};
}
"""
assert context.target_code == expected_target_code
# EMAIL_REGEX should be in read_only_context - exact match
expected_read_only = "const EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;"
assert context.read_only_context == expected_read_only
class TestGlobalVariablesAndConstants:
"""Tests for global variables and constants extraction with strict assertions."""
def test_function_with_multiple_complex_constants(self, js_support, temp_project):
"""Test function using multiple global constants of different types."""
code = """\
const API_BASE_URL = 'https://api.example.com/v2';
const DEFAULT_TIMEOUT = 30000;
const MAX_RETRIES = 3;
const RETRY_DELAYS = [1000, 2000, 4000];
const HTTP_STATUS = {
OK: 200,
CREATED: 201,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
NOT_FOUND: 404,
SERVER_ERROR: 500
};
const UNUSED_CONFIG = { debug: false };
export async function fetchWithRetry(endpoint, options = {}) {
const url = API_BASE_URL + endpoint;
let lastError;
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
try {
const response = await fetch(url, {
...options,
timeout: DEFAULT_TIMEOUT
});
if (response.status === HTTP_STATUS.OK) {
return response.json();
}
if (response.status >= HTTP_STATUS.SERVER_ERROR) {
throw new Error('Server error');
}
return null;
} catch (error) {
lastError = error;
if (attempt < MAX_RETRIES - 1) {
await new Promise(r => setTimeout(r, RETRY_DELAYS[attempt]));
}
}
}
throw lastError;
}
"""
file_path = temp_project / "api.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
func = next(f for f in functions if f.function_name == "fetchWithRetry")
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export async function fetchWithRetry(endpoint, options = {}) {
const url = API_BASE_URL + endpoint;
let lastError;
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
try {
const response = await fetch(url, {
...options,
timeout: DEFAULT_TIMEOUT
});
if (response.status === HTTP_STATUS.OK) {
return response.json();
}
if (response.status >= HTTP_STATUS.SERVER_ERROR) {
throw new Error('Server error');
}
return null;
} catch (error) {
lastError = error;
if (attempt < MAX_RETRIES - 1) {
await new Promise(r => setTimeout(r, RETRY_DELAYS[attempt]));
}
}
}
throw lastError;
}
"""
assert context.target_code == expected_target_code
# All used constants should be in read_only_context - exact match
expected_read_only = """\
const API_BASE_URL = 'https://api.example.com/v2';
const DEFAULT_TIMEOUT = 30000;
const MAX_RETRIES = 3;
const RETRY_DELAYS = [1000, 2000, 4000];
const HTTP_STATUS = {
OK: 200,
CREATED: 201,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
NOT_FOUND: 404,
SERVER_ERROR: 500
};"""
assert context.read_only_context == expected_read_only
def test_function_with_regex_and_template_constants(self, js_support, temp_project):
"""Test function with regex patterns and template literal constants."""
code = """\
const PATTERNS = {
email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/,
phone: /^\\+?[1-9]\\d{1,14}$/,
url: /^https?:\\/\\/[^\\s/$.?#].[^\\s]*$/i
};
const ERROR_MESSAGES = {
email: 'Please enter a valid email address',
phone: 'Please enter a valid phone number',
url: 'Please enter a valid URL'
};
export function validateField(value, fieldType) {
const pattern = PATTERNS[fieldType];
if (!pattern) {
return { valid: true, error: null };
}
const valid = pattern.test(value);
return {
valid,
error: valid ? null : ERROR_MESSAGES[fieldType]
};
}
"""
file_path = temp_project / "validation.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
func = functions[0]
context = js_support.extract_code_context(func, temp_project, temp_project)
expected_target_code = """\
export function validateField(value, fieldType) {
const pattern = PATTERNS[fieldType];
if (!pattern) {
return { valid: true, error: null };
}
const valid = pattern.test(value);
return {
valid,
error: valid ? null : ERROR_MESSAGES[fieldType]
};
}
"""
assert context.target_code == expected_target_code
# Exact match for read_only_context (globals joined with single newline)
expected_read_only = """\
const PATTERNS = {
email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/,
phone: /^\\+?[1-9]\\d{1,14}$/,
url: /^https?:\\/\\/[^\\s/$.?#].[^\\s]*$/i
};
const ERROR_MESSAGES = {
email: 'Please enter a valid email address',
phone: 'Please enter a valid phone number',
url: 'Please enter a valid URL'
};"""
assert context.read_only_context == expected_read_only
class TestSameFileHelperFunctions:
"""Tests for helper functions discovery within the same file."""
def test_function_with_chain_of_helpers(self, js_support, temp_project):
"""Test function calling helper that calls another helper (transitive dependencies)."""
code = """\
export function sanitizeString(str) {
return str.trim().toLowerCase();
}
export function normalizeInput(input) {
const sanitized = sanitizeString(input);
return sanitized.replace(/\\s+/g, '-');
}
export function processUserInput(rawInput) {
const normalized = normalizeInput(rawInput);
return {
original: rawInput,
processed: normalized,
length: normalized.length
};
}
"""
file_path = temp_project / "processor.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
process_func = next(f for f in functions if f.function_name == "processUserInput")
context = js_support.extract_code_context(process_func, temp_project, temp_project)
expected_target_code = """\
export function processUserInput(rawInput) {
const normalized = normalizeInput(rawInput);
return {
original: rawInput,
processed: normalized,
length: normalized.length
};
}
"""
assert context.target_code == expected_target_code
# Direct helper normalizeInput should be found - exact list match
helper_names = [h.name for h in context.helper_functions]
assert helper_names == ["normalizeInput"]
def test_function_with_multiple_unrelated_helpers(self, js_support, temp_project):
"""Test function calling multiple independent helper functions."""
code = """\
export function formatDate(date) {
return date.toISOString().split('T')[0];
}
export function formatCurrency(amount) {
return '$' + amount.toFixed(2);
}
export function formatPercentage(value) {
return (value * 100).toFixed(1) + '%';
}
export function unusedFormatter() {
return 'not used';
}
export function generateReport(data) {
const date = formatDate(new Date(data.timestamp));
const revenue = formatCurrency(data.revenue);
const growth = formatPercentage(data.growth);
return {
reportDate: date,
totalRevenue: revenue,
growthRate: growth
};
}
"""
file_path = temp_project / "report.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
report_func = next(f for f in functions if f.function_name == "generateReport")
context = js_support.extract_code_context(report_func, temp_project, temp_project)
expected_target_code = """\
export function generateReport(data) {
const date = formatDate(new Date(data.timestamp));
const revenue = formatCurrency(data.revenue);
const growth = formatPercentage(data.growth);
return {
reportDate: date,
totalRevenue: revenue,
growthRate: growth
};
}
"""
assert context.target_code == expected_target_code
# All three used helpers should be found
helper_names = sorted([h.name for h in context.helper_functions])
assert helper_names == ["formatCurrency", "formatDate", "formatPercentage"]
# Verify helper source code exactly
for helper in context.helper_functions:
if helper.name == "formatDate":
expected = """\
export function formatDate(date) {
return date.toISOString().split('T')[0];
}
"""
assert helper.source_code == expected
elif helper.name == "formatCurrency":
expected = """\
export function formatCurrency(amount) {
return '$' + amount.toFixed(2);
}
"""
assert helper.source_code == expected
elif helper.name == "formatPercentage":
expected = """\
export function formatPercentage(value) {
return (value * 100).toFixed(1) + '%';
}
"""
assert helper.source_code == expected
class TestClassMethodWithSiblingMethods:
"""Tests for class methods calling other methods in the same class."""
def test_graph_topological_sort(self, js_support, temp_project):
"""Test graph class with topological sort - similar to Python test_class_method_dependencies."""
code = """\
export class Graph {
constructor(vertices) {
this.graph = new Map();
this.V = vertices;
}
addEdge(u, v) {
if (!this.graph.has(u)) {
this.graph.set(u, []);
}
this.graph.get(u).push(v);
}
topologicalSortUtil(v, visited, stack) {
visited[v] = true;
const neighbors = this.graph.get(v) || [];
for (const i of neighbors) {
if (visited[i] === false) {
this.topologicalSortUtil(i, visited, stack);
}
}
stack.unshift(v);
}
topologicalSort() {
const visited = new Array(this.V).fill(false);
const stack = [];
for (let i = 0; i < this.V; i++) {
if (visited[i] === false) {
this.topologicalSortUtil(i, visited, stack);
}
}
return stack;
}
}
"""
file_path = temp_project / "graph.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
topo_sort = next(f for f in functions if f.function_name == "topologicalSort")
context = js_support.extract_code_context(topo_sort, temp_project, temp_project)
# The extracted code should include class wrapper with constructor and sibling methods used
expected_target_code = """\
class Graph {
constructor(vertices) {
this.graph = new Map();
this.V = vertices;
}
topologicalSort() {
const visited = new Array(this.V).fill(false);
const stack = [];
for (let i = 0; i < this.V; i++) {
if (visited[i] === false) {
this.topologicalSortUtil(i, visited, stack);
}
}
return stack;
}
topologicalSortUtil(v, visited, stack) {
visited[v] = true;
const neighbors = this.graph.get(v) || [];
for (const i of neighbors) {
if (visited[i] === false) {
this.topologicalSortUtil(i, visited, stack);
}
}
stack.unshift(v);
}
}
"""
assert context.target_code == expected_target_code
assert js_support.validate_syntax(context.target_code) is True
def test_class_method_using_nested_helper_class(self, js_support, temp_project):
"""Test class method that uses another class as a helper - mirrors Python HelperClass test."""
code = """\
export class HelperClass {
constructor(name) {
this.name = name;
}
innocentBystander() {
return 'not used';
}
helperMethod() {
return this.name;
}
}
export class NestedHelper {
constructor(name) {
this.name = name;
}
nestedMethod() {
return this.name;
}
}
export function mainMethod() {
return 'hello';
}
export class MainClass {
constructor(name) {
this.name = name;
}
mainMethod() {
this.name = new NestedHelper('test').nestedMethod();
return new HelperClass(this.name).helperMethod();
}
}
"""
file_path = temp_project / "classes.js"
file_path.write_text(code, encoding="utf-8")
source = file_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, file_path)
main_method = next(f for f in functions if f.function_name == "mainMethod" and f.class_name == "MainClass")
context = js_support.extract_code_context(main_method, temp_project, temp_project)
expected_target_code = """\
class MainClass {
constructor(name) {
this.name = name;
}
mainMethod() {
this.name = new NestedHelper('test').nestedMethod();
return new HelperClass(this.name).helperMethod();
}
}
"""
assert context.target_code == expected_target_code
assert js_support.validate_syntax(context.target_code) is True
class TestMultiFileHelperExtraction:
"""Tests for helper functions extracted from imported files."""
def test_helper_from_another_file_commonjs(self, js_support, temp_project):
"""Test function importing helper from another file via CommonJS - mirrors Python bubble_sort_helper."""
# Create helper file with its own import
helper_code = """\
const mathUtils = require('./math_utils');
function sorter(arr) {
arr.sort();
const x = mathUtils.sqrt(2);
console.log(x);
return arr;
}
module.exports = { sorter };
"""
helper_path = temp_project / "bubble_sort_with_math.js"
helper_path.write_text(helper_code, encoding="utf-8")
# Create main file that imports the helper
main_code = """\
const { sorter } = require('./bubble_sort_with_math');
export function sortFromAnotherFile(arr) {
const sortedArr = sorter(arr);
return sortedArr;
}
module.exports = { sortFromAnotherFile };
"""
main_path = temp_project / "bubble_sort_imported.js"
main_path.write_text(main_code, encoding="utf-8")
source = main_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, main_path)
main_func = next(f for f in functions if f.function_name == "sortFromAnotherFile")
context = js_support.extract_code_context(main_func, temp_project, temp_project)
expected_target_code = """\
export function sortFromAnotherFile(arr) {
const sortedArr = sorter(arr);
return sortedArr;
}
"""
assert context.target_code == expected_target_code
# Import should be captured - exact match
assert context.imports == ["const { sorter } = require('./bubble_sort_with_math');"]
def test_helper_from_another_file_esm(self, js_support, temp_project):
"""Test ES module imports with named and default exports."""
# Create utility module with multiple exports
utils_code = """\
export function double(x) {
return x * 2;
}
export function triple(x) {
return x * 3;
}
export function square(x) {
return x * x;
}
export default function identity(x) {
return x;
}
"""
utils_path = temp_project / "utils.js"
utils_path.write_text(utils_code, encoding="utf-8")
# Create main module with selective imports
main_code = """\
import identity, { double, triple } from './utils';
export function processNumber(n) {
const base = identity(n);
return double(base) + triple(base);
}
"""
main_path = temp_project / "main.js"
main_path.write_text(main_code, encoding="utf-8")
source = main_path.read_text(encoding="utf-8")
functions = js_support.discover_functions(source, main_path)
process_func = next(f for f in functions if f.function_name == "processNumber")
context = js_support.extract_code_context(process_func, temp_project, temp_project)
expected_target_code = """\
export function processNumber(n) {
const base = identity(n);
return double(base) + triple(base);
}
"""
assert context.target_code == expected_target_code
# Import should be captured - exact match
assert context.imports == ["import identity, { double, triple } from './utils';"]
def test_chained_imports_across_three_files(self, js_support, temp_project):
"""Test helper chain: main -> middleware -> core."""
# Create core utility
core_code = """\
export function validateInput(input) {
return input !== null && input !== undefined;
}
export function sanitizeInput(input) {
return String(input).trim();
}
"""
core_path = temp_project / "core.js"
core_path.write_text(core_code, encoding="utf-8")
# Create middleware that uses core
middleware_code = """\
import { validateInput, sanitizeInput } from './core';
export function processInput(input) {
if (!validateInput(input)) {
throw new Error('Invalid input');
}
return sanitizeInput(input);
}
export function transformInput(input) {
const processed = processInput(input);
return processed.toUpperCase();
}
"""
middleware_path = temp_project / "middleware.js"
middleware_path.write_text(middleware_code, encoding="utf-8")
# Create main that uses middleware
main_code = """\
import { transformInput } from './middleware';
export function handleUserInput(rawInput) {