forked from Aider-AI/aider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_editblock.py
580 lines (459 loc) · 15.8 KB
/
test_editblock.py
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
# flake8: noqa: E501
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from aider.coders import Coder
from aider.coders import editblock_coder as eb
from aider.dump import dump # noqa: F401
from aider.io import InputOutput
from aider.models import Model
from aider.utils import ChdirTemporaryDirectory
class TestUtils(unittest.TestCase):
def setUp(self):
self.GPT35 = Model("gpt-3.5-turbo")
def test_find_filename(self):
fence = ("```", "```")
valid_fnames = ["file1.py", "file2.py", "dir/file3.py", r"\windows\__init__.py"]
# Test with filename on a single line
lines = ["file1.py", "```"]
self.assertEqual(eb.find_filename(lines, fence, valid_fnames), "file1.py")
# Test with filename in fence
lines = ["```python", "file3.py", "```"]
self.assertEqual(eb.find_filename(lines, fence, valid_fnames), "dir/file3.py")
# Test with no valid filename
lines = ["```", "invalid_file.py", "```"]
self.assertEqual("invalid_file.py", eb.find_filename(lines, fence, valid_fnames))
# Test with multiple fences
lines = ["```python", "file1.py", "```", "```", "file2.py", "```"]
self.assertEqual(eb.find_filename(lines, fence, valid_fnames), "file2.py")
# Test with filename having extra characters
lines = ["# file1.py", "```"]
self.assertEqual(eb.find_filename(lines, fence, valid_fnames), "file1.py")
# Test with fuzzy matching
lines = ["file1_py", "```"]
self.assertEqual(eb.find_filename(lines, fence, valid_fnames), "file1.py")
# Test with fuzzy matching
lines = [r"\windows__init__.py", "```"]
self.assertEqual(eb.find_filename(lines, fence, valid_fnames), r"\windows\__init__.py")
# fuzzy logic disabled v0.11.2-dev
def __test_replace_most_similar_chunk(self):
whole = "This is a sample text.\nAnother line of text.\nYet another line.\n"
part = "This is a sample text\n"
replace = "This is a replaced text.\n"
expected_output = "This is a replaced text.\nAnother line of text.\nYet another line.\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
# fuzzy logic disabled v0.11.2-dev
def __test_replace_most_similar_chunk_not_perfect_match(self):
whole = "This is a sample text.\nAnother line of text.\nYet another line.\n"
part = "This was a sample text.\nAnother line of txt\n"
replace = "This is a replaced text.\nModified line of text.\n"
expected_output = "This is a replaced text.\nModified line of text.\nYet another line.\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_strip_quoted_wrapping(self):
input_text = (
"filename.ext\n```\nWe just want this content\nNot the filename and triple quotes\n```"
)
expected_output = "We just want this content\nNot the filename and triple quotes\n"
result = eb.strip_quoted_wrapping(input_text, "filename.ext")
self.assertEqual(result, expected_output)
def test_strip_quoted_wrapping_no_filename(self):
input_text = "```\nWe just want this content\nNot the triple quotes\n```"
expected_output = "We just want this content\nNot the triple quotes\n"
result = eb.strip_quoted_wrapping(input_text)
self.assertEqual(result, expected_output)
def test_strip_quoted_wrapping_no_wrapping(self):
input_text = "We just want this content\nNot the triple quotes\n"
expected_output = "We just want this content\nNot the triple quotes\n"
result = eb.strip_quoted_wrapping(input_text)
self.assertEqual(result, expected_output)
def test_find_original_update_blocks(self):
edit = """
Here's the change:
```text
foo.txt
<<<<<<< SEARCH
Two
=======
Tooooo
>>>>>>> REPLACE
```
Hope you like it!
"""
edits = list(eb.find_original_update_blocks(edit))
self.assertEqual(edits, [("foo.txt", "Two\n", "Tooooo\n")])
def test_find_original_update_blocks_mangled_filename_w_source_tag(self):
source = "source"
edit = """
Here's the change:
<%s>foo.txt
<<<<<<< SEARCH
One
=======
Two
>>>>>>> REPLACE
</%s>
Hope you like it!
""" % (source, source)
fence = ("<%s>" % source, "</%s>" % source)
with self.assertRaises(ValueError) as cm:
_edits = list(eb.find_original_update_blocks(edit, fence))
self.assertIn("missing filename", str(cm.exception))
def test_find_original_update_blocks_quote_below_filename(self):
edit = """
Here's the change:
foo.txt
```text
<<<<<<< SEARCH
Two
=======
Tooooo
>>>>>>> REPLACE
```
Hope you like it!
"""
edits = list(eb.find_original_update_blocks(edit))
self.assertEqual(edits, [("foo.txt", "Two\n", "Tooooo\n")])
def test_find_original_update_blocks_unclosed(self):
edit = """
Here's the change:
```text
foo.txt
<<<<<<< SEARCH
Two
=======
Tooooo
oops!
"""
with self.assertRaises(ValueError) as cm:
list(eb.find_original_update_blocks(edit))
self.assertIn("Expected `>>>>>>> REPLACE` or `=======`", str(cm.exception))
def test_find_original_update_blocks_missing_filename(self):
edit = """
Here's the change:
```text
<<<<<<< SEARCH
Two
=======
Tooooo
oops!
"""
with self.assertRaises(ValueError) as cm:
list(eb.find_original_update_blocks(edit))
self.assertIn("filename", str(cm.exception))
def test_find_original_update_blocks_no_final_newline(self):
edit = """
aider/coder.py
<<<<<<< SEARCH
self.console.print("[red]^C again to quit")
=======
self.io.tool_error("^C again to quit")
>>>>>>> REPLACE
aider/coder.py
<<<<<<< SEARCH
self.io.tool_error("Malformed ORIGINAL/UPDATE blocks, retrying...")
self.io.tool_error(err)
=======
self.io.tool_error("Malformed ORIGINAL/UPDATE blocks, retrying...")
self.io.tool_error(str(err))
>>>>>>> REPLACE
aider/coder.py
<<<<<<< SEARCH
self.console.print("[red]Unable to get commit message from gpt-3.5-turbo. Use /commit to try again.\n")
=======
self.io.tool_error("Unable to get commit message from gpt-3.5-turbo. Use /commit to try again.")
>>>>>>> REPLACE
aider/coder.py
<<<<<<< SEARCH
self.console.print("[red]Skipped commit.")
=======
self.io.tool_error("Skipped commit.")
>>>>>>> REPLACE"""
# Should not raise a ValueError
list(eb.find_original_update_blocks(edit))
def test_incomplete_edit_block_missing_filename(self):
edit = """
No problem! Here are the changes to patch `subprocess.check_output` instead of `subprocess.run` in both tests:
```python
tests/test_repomap.py
<<<<<<< SEARCH
def test_check_for_ctags_failure(self):
with patch("subprocess.run") as mock_run:
mock_run.side_effect = Exception("ctags not found")
=======
def test_check_for_ctags_failure(self):
with patch("subprocess.check_output") as mock_check_output:
mock_check_output.side_effect = Exception("ctags not found")
>>>>>>> REPLACE
<<<<<<< SEARCH
def test_check_for_ctags_success(self):
with patch("subprocess.run") as mock_run:
mock_run.return_value = CompletedProcess(args=["ctags", "--version"], returncode=0, stdout='''{
"_type": "tag",
"name": "status",
"path": "aider/main.py",
"pattern": "/^ status = main()$/",
"kind": "variable"
}''')
=======
def test_check_for_ctags_success(self):
with patch("subprocess.check_output") as mock_check_output:
mock_check_output.return_value = '''{
"_type": "tag",
"name": "status",
"path": "aider/main.py",
"pattern": "/^ status = main()$/",
"kind": "variable"
}'''
>>>>>>> REPLACE
```
These changes replace the `subprocess.run` patches with `subprocess.check_output` patches in both `test_check_for_ctags_failure` and `test_check_for_ctags_success` tests.
"""
edit_blocks = list(eb.find_original_update_blocks(edit))
self.assertEqual(len(edit_blocks), 2) # 2 edits
self.assertEqual(edit_blocks[0][0], "tests/test_repomap.py")
self.assertEqual(edit_blocks[1][0], "tests/test_repomap.py")
def test_replace_part_with_missing_varied_leading_whitespace(self):
whole = """
line1
line2
line3
line4
"""
part = "line2\n line3\n"
replace = "new_line2\n new_line3\n"
expected_output = """
line1
new_line2
new_line3
line4
"""
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_replace_part_with_missing_leading_whitespace(self):
whole = " line1\n line2\n line3\n"
part = "line1\nline2\n"
replace = "new_line1\nnew_line2\n"
expected_output = " new_line1\n new_line2\n line3\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_replace_multiple_matches(self):
"only replace first occurrence"
whole = "line1\nline2\nline1\nline3\n"
part = "line1\n"
replace = "new_line\n"
expected_output = "new_line\nline2\nline1\nline3\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_replace_multiple_matches_missing_whitespace(self):
"only replace first occurrence"
whole = " line1\n line2\n line1\n line3\n"
part = "line1\n"
replace = "new_line\n"
expected_output = " new_line\n line2\n line1\n line3\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_replace_part_with_just_some_missing_leading_whitespace(self):
whole = " line1\n line2\n line3\n"
part = " line1\n line2\n"
replace = " new_line1\n new_line2\n"
expected_output = " new_line1\n new_line2\n line3\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_replace_part_with_missing_leading_whitespace_including_blank_line(self):
"""
The part has leading whitespace on all lines, so should be ignored.
But it has a *blank* line with no whitespace at all, which was causing a
bug per issue #25. Test case to repro and confirm fix.
"""
whole = " line1\n line2\n line3\n"
part = "\n line1\n line2\n"
replace = " new_line1\n new_line2\n"
expected_output = " new_line1\n new_line2\n line3\n"
result = eb.replace_most_similar_chunk(whole, part, replace)
self.assertEqual(result, expected_output)
def test_create_new_file_with_other_file_in_chat(self):
# https://github.com/Aider-AI/aider/issues/2258
with ChdirTemporaryDirectory():
# Create a few temporary files
file1 = "file.txt"
with open(file1, "w", encoding="utf-8") as f:
f.write("one\ntwo\nthree\n")
files = [file1]
# Initialize the Coder object with the mocked IO and mocked repo
coder = Coder.create(
self.GPT35, "diff", use_git=False, io=InputOutput(yes=True), fnames=files
)
def mock_send(*args, **kwargs):
coder.partial_response_content = f"""
Do this:
newfile.txt
<<<<<<< SEARCH
=======
creating a new file
>>>>>>> REPLACE
"""
coder.partial_response_function_call = dict()
return []
coder.send = mock_send
coder.run(with_message="hi")
content = Path(file1).read_text(encoding="utf-8")
self.assertEqual(content, "one\ntwo\nthree\n")
content = Path("newfile.txt").read_text(encoding="utf-8")
self.assertEqual(content, "creating a new file\n")
def test_full_edit(self):
# Create a few temporary files
_, file1 = tempfile.mkstemp()
with open(file1, "w", encoding="utf-8") as f:
f.write("one\ntwo\nthree\n")
files = [file1]
# Initialize the Coder object with the mocked IO and mocked repo
coder = Coder.create(self.GPT35, "diff", io=InputOutput(), fnames=files)
def mock_send(*args, **kwargs):
coder.partial_response_content = f"""
Do this:
{Path(file1).name}
<<<<<<< SEARCH
two
=======
new
>>>>>>> REPLACE
"""
coder.partial_response_function_call = dict()
return []
coder.send = mock_send
# Call the run method with a message
coder.run(with_message="hi")
content = Path(file1).read_text(encoding="utf-8")
self.assertEqual(content, "one\nnew\nthree\n")
def test_full_edit_dry_run(self):
# Create a few temporary files
_, file1 = tempfile.mkstemp()
orig_content = "one\ntwo\nthree\n"
with open(file1, "w", encoding="utf-8") as f:
f.write(orig_content)
files = [file1]
# Initialize the Coder object with the mocked IO and mocked repo
coder = Coder.create(
self.GPT35,
"diff",
io=InputOutput(dry_run=True),
fnames=files,
dry_run=True,
)
def mock_send(*args, **kwargs):
coder.partial_response_content = f"""
Do this:
{Path(file1).name}
<<<<<<< SEARCH
two
=======
new
>>>>>>> REPLACE
"""
coder.partial_response_function_call = dict()
return []
coder.send = mock_send
# Call the run method with a message
coder.run(with_message="hi")
content = Path(file1).read_text(encoding="utf-8")
self.assertEqual(content, orig_content)
def test_find_original_update_blocks_mupltiple_same_file(self):
edit = """
Here's the change:
```text
foo.txt
<<<<<<< SEARCH
one
=======
two
>>>>>>> REPLACE
...
<<<<<<< SEARCH
three
=======
four
>>>>>>> REPLACE
```
Hope you like it!
"""
edits = list(eb.find_original_update_blocks(edit))
self.assertEqual(
edits,
[
("foo.txt", "one\n", "two\n"),
("foo.txt", "three\n", "four\n"),
],
)
def test_deepseek_coder_v2_filename_mangling(self):
edit = """
Here's the change:
```python
foo.txt
```
```python
<<<<<<< SEARCH
one
=======
two
>>>>>>> REPLACE
```
Hope you like it!
"""
edits = list(eb.find_original_update_blocks(edit))
self.assertEqual(
edits,
[
("foo.txt", "one\n", "two\n"),
],
)
def test_new_file_created_in_same_folder(self):
edit = """
Here's the change:
path/to/a/file2.txt
```python
<<<<<<< SEARCH
=======
three
>>>>>>> REPLACE
```
another change
path/to/a/file1.txt
```python
<<<<<<< SEARCH
one
=======
two
>>>>>>> REPLACE
```
Hope you like it!
"""
edits = list(eb.find_original_update_blocks(edit, valid_fnames=["path/to/a/file1.txt"]))
self.assertEqual(
edits,
[
("path/to/a/file2.txt", "", "three\n"),
("path/to/a/file1.txt", "one\n", "two\n"),
],
)
def test_find_original_update_blocks_quad_backticks_with_triples_in_LLM_reply(self):
# https://github.com/Aider-AI/aider/issues/2879
edit = """
Here's the change:
foo.txt
```text
<<<<<<< SEARCH
=======
Tooooo
>>>>>>> REPLACE
```
Hope you like it!
"""
quad_backticks = "`" * 4
quad_backticks = (quad_backticks, quad_backticks)
edits = list(eb.find_original_update_blocks(edit, fence=quad_backticks))
self.assertEqual(edits, [("foo.txt", "", "Tooooo\n")])
if __name__ == "__main__":
unittest.main()