-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Expand file tree
/
Copy pathtest_main.py
More file actions
1496 lines (1284 loc) · 61.6 KB
/
Copy pathtest_main.py
File metadata and controls
1496 lines (1284 loc) · 61.6 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
import contextlib
import json
import os
import subprocess
import tempfile
from io import StringIO
from pathlib import Path
from unittest import TestCase
from unittest.mock import MagicMock, patch
import git
from prompt_toolkit.input import DummyInput
from prompt_toolkit.output import DummyOutput
from aider.coders import Coder
from aider.dump import dump # noqa: F401
from aider.io import InputOutput
from aider.main import check_gitignore, load_dotenv_files, main, setup_git
from aider.utils import GitTemporaryDirectory, IgnorantTemporaryDirectory, make_repo
class TestMain(TestCase):
def setUp(self):
self.original_env = os.environ.copy()
os.environ["OPENAI_API_KEY"] = "deadbeef"
os.environ["AIDER_CHECK_UPDATE"] = "false"
os.environ["AIDER_ANALYTICS"] = "false"
self.original_cwd = os.getcwd()
self.tempdir_obj = IgnorantTemporaryDirectory()
self.tempdir = self.tempdir_obj.name
os.chdir(self.tempdir)
# Fake home directory prevents tests from using the real ~/.aider.conf.yml file:
self.homedir_obj = IgnorantTemporaryDirectory()
os.environ["HOME"] = self.homedir_obj.name
self.input_patcher = patch("builtins.input", return_value=None)
self.mock_input = self.input_patcher.start()
self.webbrowser_patcher = patch("aider.io.webbrowser.open")
self.mock_webbrowser = self.webbrowser_patcher.start()
def tearDown(self):
os.chdir(self.original_cwd)
self.tempdir_obj.cleanup()
self.homedir_obj.cleanup()
os.environ.clear()
os.environ.update(self.original_env)
self.input_patcher.stop()
self.webbrowser_patcher.stop()
def test_main_with_empty_dir_no_files_on_command(self):
main(["--no-git", "--exit", "--yes"], input=DummyInput(), output=DummyOutput())
def test_main_with_emptqy_dir_new_file(self):
main(["foo.txt", "--yes", "--no-git", "--exit"], input=DummyInput(), output=DummyOutput())
self.assertTrue(os.path.exists("foo.txt"))
@patch("aider.repo.GitRepo.get_commit_message", return_value="mock commit message")
def test_main_with_empty_git_dir_new_file(self, _):
make_repo()
main(["--yes", "foo.txt", "--exit"], input=DummyInput(), output=DummyOutput())
self.assertTrue(os.path.exists("foo.txt"))
@patch("aider.repo.GitRepo.get_commit_message", return_value="mock commit message")
def test_main_with_empty_git_dir_new_files(self, _):
make_repo()
main(["--yes", "foo.txt", "bar.txt", "--exit"], input=DummyInput(), output=DummyOutput())
self.assertTrue(os.path.exists("foo.txt"))
self.assertTrue(os.path.exists("bar.txt"))
def test_main_with_dname_and_fname(self):
subdir = Path("subdir")
subdir.mkdir()
make_repo(str(subdir))
res = main(["subdir", "foo.txt"], input=DummyInput(), output=DummyOutput())
self.assertNotEqual(res, None)
@patch("aider.repo.GitRepo.get_commit_message", return_value="mock commit message")
def test_main_with_subdir_repo_fnames(self, _):
subdir = Path("subdir")
subdir.mkdir()
make_repo(str(subdir))
main(
["--yes", str(subdir / "foo.txt"), str(subdir / "bar.txt"), "--exit"],
input=DummyInput(),
output=DummyOutput(),
)
self.assertTrue((subdir / "foo.txt").exists())
self.assertTrue((subdir / "bar.txt").exists())
def test_main_with_git_config_yml(self):
make_repo()
Path(".aider.conf.yml").write_text("auto-commits: false\n")
with patch("aider.coders.Coder.create") as MockCoder:
main(["--yes"], input=DummyInput(), output=DummyOutput())
_, kwargs = MockCoder.call_args
assert kwargs["auto_commits"] is False
Path(".aider.conf.yml").write_text("auto-commits: true\n")
with patch("aider.coders.Coder.create") as MockCoder:
main([], input=DummyInput(), output=DummyOutput())
_, kwargs = MockCoder.call_args
assert kwargs["auto_commits"] is True
def test_main_with_unreadable_config_file(self):
# A directory named .aider.conf.yml can not be opened as a config file.
# aider should print a friendly error and exit non-zero instead of
# dumping an uncaught PermissionError/IsADirectoryError traceback.
# https://github.com/Aider-AI/aider/issues/5466
Path(".aider.conf.yml").mkdir()
stdout = StringIO()
with contextlib.redirect_stdout(stdout):
result = main(["--exit"], input=DummyInput(), output=DummyOutput())
self.assertEqual(result, 1)
self.assertIn("Unable to read configuration file", stdout.getvalue())
def test_main_with_empty_git_dir_new_subdir_file(self):
make_repo()
subdir = Path("subdir")
subdir.mkdir()
fname = subdir / "foo.txt"
fname.touch()
subprocess.run(["git", "add", str(subdir)])
subprocess.run(["git", "commit", "-m", "added"])
# This will throw a git error on windows if get_tracked_files doesn't
# properly convert git/posix/paths to git\posix\paths.
# Because aider will try and `git add` a file that's already in the repo.
main(["--yes", str(fname), "--exit"], input=DummyInput(), output=DummyOutput())
def test_setup_git(self):
io = InputOutput(pretty=False, yes=True)
git_root = setup_git(None, io)
git_root = Path(git_root).resolve()
self.assertEqual(git_root, Path(self.tempdir).resolve())
self.assertTrue(git.Repo(self.tempdir))
gitignore = Path.cwd() / ".gitignore"
self.assertTrue(gitignore.exists())
self.assertEqual(".aider*", gitignore.read_text().splitlines()[0])
def test_check_gitignore(self):
with GitTemporaryDirectory():
os.environ["GIT_CONFIG_GLOBAL"] = "globalgitconfig"
io = InputOutput(pretty=False, yes=True)
cwd = Path.cwd()
gitignore = cwd / ".gitignore"
self.assertFalse(gitignore.exists())
check_gitignore(cwd, io)
self.assertTrue(gitignore.exists())
self.assertEqual(".aider*", gitignore.read_text().splitlines()[0])
# Test without .env file present
gitignore.write_text("one\ntwo\n")
check_gitignore(cwd, io)
self.assertEqual("one\ntwo\n.aider*\n", gitignore.read_text())
# Test with .env file present
env_file = cwd / ".env"
env_file.touch()
check_gitignore(cwd, io)
self.assertEqual("one\ntwo\n.aider*\n.env\n", gitignore.read_text())
del os.environ["GIT_CONFIG_GLOBAL"]
def test_command_line_gitignore_files_flag(self):
with GitTemporaryDirectory() as git_dir:
git_dir = Path(git_dir)
# Create a .gitignore file
gitignore_file = git_dir / ".gitignore"
gitignore_file.write_text("ignored.txt\n")
# Create an ignored file
ignored_file = git_dir / "ignored.txt"
ignored_file.write_text("This file should be ignored.")
# Get the absolute path to the ignored file
abs_ignored_file = str(ignored_file.resolve())
# Test without the --add-gitignore-files flag (default: False)
coder = main(
["--exit", "--yes", abs_ignored_file],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
force_git_root=git_dir,
)
# Verify the ignored file is not in the chat
self.assertNotIn(abs_ignored_file, coder.abs_fnames)
# Test with --add-gitignore-files set to True
coder = main(
["--add-gitignore-files", "--exit", "--yes", abs_ignored_file],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
force_git_root=git_dir,
)
# Verify the ignored file is in the chat
self.assertIn(abs_ignored_file, coder.abs_fnames)
# Test with --add-gitignore-files set to False
coder = main(
["--no-add-gitignore-files", "--exit", "--yes", abs_ignored_file],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
force_git_root=git_dir,
)
# Verify the ignored file is not in the chat
self.assertNotIn(abs_ignored_file, coder.abs_fnames)
def test_add_command_gitignore_files_flag(self):
with GitTemporaryDirectory() as git_dir:
git_dir = Path(git_dir)
# Create a .gitignore file
gitignore_file = git_dir / ".gitignore"
gitignore_file.write_text("ignored.txt\n")
# Create an ignored file
ignored_file = git_dir / "ignored.txt"
ignored_file.write_text("This file should be ignored.")
# Get the absolute path to the ignored file
abs_ignored_file = str(ignored_file.resolve())
rel_ignored_file = "ignored.txt"
# Test without the --add-gitignore-files flag (default: False)
coder = main(
["--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
force_git_root=git_dir,
)
with patch.object(coder.io, "confirm_ask", return_value=True):
coder.commands.cmd_add(rel_ignored_file)
# Verify the ignored file is not in the chat
self.assertNotIn(abs_ignored_file, coder.abs_fnames)
# Test with --add-gitignore-files set to True
coder = main(
["--add-gitignore-files", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
force_git_root=git_dir,
)
with patch.object(coder.io, "confirm_ask", return_value=True):
coder.commands.cmd_add(rel_ignored_file)
# Verify the ignored file is in the chat
self.assertIn(abs_ignored_file, coder.abs_fnames)
# Test with --add-gitignore-files set to False
coder = main(
["--no-add-gitignore-files", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
force_git_root=git_dir,
)
with patch.object(coder.io, "confirm_ask", return_value=True):
coder.commands.cmd_add(rel_ignored_file)
# Verify the ignored file is not in the chat
self.assertNotIn(abs_ignored_file, coder.abs_fnames)
def test_main_args(self):
with patch("aider.coders.Coder.create") as MockCoder:
# --yes will just ok the git repo without blocking on input
# following calls to main will see the new repo already
main(["--no-auto-commits", "--yes"], input=DummyInput())
_, kwargs = MockCoder.call_args
assert kwargs["auto_commits"] is False
with patch("aider.coders.Coder.create") as MockCoder:
main(["--auto-commits"], input=DummyInput())
_, kwargs = MockCoder.call_args
assert kwargs["auto_commits"] is True
with patch("aider.coders.Coder.create") as MockCoder:
main([], input=DummyInput())
_, kwargs = MockCoder.call_args
assert kwargs["dirty_commits"] is True
assert kwargs["auto_commits"] is True
with patch("aider.coders.Coder.create") as MockCoder:
main(["--no-dirty-commits"], input=DummyInput())
_, kwargs = MockCoder.call_args
assert kwargs["dirty_commits"] is False
with patch("aider.coders.Coder.create") as MockCoder:
main(["--dirty-commits"], input=DummyInput())
_, kwargs = MockCoder.call_args
assert kwargs["dirty_commits"] is True
def test_env_file_override(self):
with GitTemporaryDirectory() as git_dir:
git_dir = Path(git_dir)
git_env = git_dir / ".env"
fake_home = git_dir / "fake_home"
fake_home.mkdir()
os.environ["HOME"] = str(fake_home)
home_env = fake_home / ".env"
cwd = git_dir / "subdir"
cwd.mkdir()
os.chdir(cwd)
cwd_env = cwd / ".env"
named_env = git_dir / "named.env"
os.environ["E"] = "existing"
home_env.write_text("A=home\nB=home\nC=home\nD=home")
git_env.write_text("A=git\nB=git\nC=git")
cwd_env.write_text("A=cwd\nB=cwd")
named_env.write_text("A=named")
with patch("pathlib.Path.home", return_value=fake_home):
main(["--yes", "--exit", "--env-file", str(named_env)])
self.assertEqual(os.environ["A"], "named")
self.assertEqual(os.environ["B"], "cwd")
self.assertEqual(os.environ["C"], "git")
self.assertEqual(os.environ["D"], "home")
self.assertEqual(os.environ["E"], "existing")
def test_message_file_flag(self):
message_file_content = "This is a test message from a file."
message_file_path = tempfile.mktemp()
with open(message_file_path, "w", encoding="utf-8") as message_file:
message_file.write(message_file_content)
with patch("aider.coders.Coder.create") as MockCoder:
MockCoder.return_value.run = MagicMock()
main(
["--yes", "--message-file", message_file_path],
input=DummyInput(),
output=DummyOutput(),
)
MockCoder.return_value.run.assert_called_once_with(with_message=message_file_content)
os.remove(message_file_path)
def test_encodings_arg(self):
fname = "foo.py"
with GitTemporaryDirectory():
with patch("aider.coders.Coder.create") as MockCoder: # noqa: F841
with patch("aider.main.InputOutput") as MockSend:
def side_effect(*args, **kwargs):
self.assertEqual(kwargs["encoding"], "iso-8859-15")
return MagicMock()
MockSend.side_effect = side_effect
main(["--yes", fname, "--encoding", "iso-8859-15"])
def test_main_exit_calls_version_check(self):
with GitTemporaryDirectory():
with (
patch("aider.main.check_version") as mock_check_version,
patch("aider.main.InputOutput") as mock_input_output,
):
main(["--exit", "--check-update"], input=DummyInput(), output=DummyOutput())
mock_check_version.assert_called_once()
mock_input_output.assert_called_once()
@patch("aider.main.InputOutput")
@patch("aider.coders.base_coder.Coder.run")
def test_main_message_adds_to_input_history(self, mock_run, MockInputOutput):
test_message = "test message"
mock_io_instance = MockInputOutput.return_value
main(["--message", test_message], input=DummyInput(), output=DummyOutput())
mock_io_instance.add_to_input_history.assert_called_once_with(test_message)
@patch("aider.main.InputOutput")
@patch("aider.coders.base_coder.Coder.run")
def test_yes(self, mock_run, MockInputOutput):
test_message = "test message"
main(["--yes", "--message", test_message])
args, kwargs = MockInputOutput.call_args
self.assertTrue(args[1])
@patch("aider.main.InputOutput")
@patch("aider.coders.base_coder.Coder.run")
def test_default_yes(self, mock_run, MockInputOutput):
test_message = "test message"
main(["--message", test_message])
args, kwargs = MockInputOutput.call_args
self.assertEqual(args[1], None)
def test_dark_mode_sets_code_theme(self):
# Mock InputOutput to capture the configuration
with patch("aider.main.InputOutput") as MockInputOutput:
MockInputOutput.return_value.get_input.return_value = None
main(["--dark-mode", "--no-git", "--exit"], input=DummyInput(), output=DummyOutput())
# Ensure InputOutput was called
MockInputOutput.assert_called_once()
# Check if the code_theme setting is for dark mode
_, kwargs = MockInputOutput.call_args
self.assertEqual(kwargs["code_theme"], "monokai")
def test_light_mode_sets_code_theme(self):
# Mock InputOutput to capture the configuration
with patch("aider.main.InputOutput") as MockInputOutput:
MockInputOutput.return_value.get_input.return_value = None
main(["--light-mode", "--no-git", "--exit"], input=DummyInput(), output=DummyOutput())
# Ensure InputOutput was called
MockInputOutput.assert_called_once()
# Check if the code_theme setting is for light mode
_, kwargs = MockInputOutput.call_args
self.assertEqual(kwargs["code_theme"], "default")
def create_env_file(self, file_name, content):
env_file_path = Path(self.tempdir) / file_name
env_file_path.write_text(content)
return env_file_path
def test_env_file_flag_sets_automatic_variable(self):
env_file_path = self.create_env_file(".env.test", "AIDER_DARK_MODE=True")
with patch("aider.main.InputOutput") as MockInputOutput:
MockInputOutput.return_value.get_input.return_value = None
MockInputOutput.return_value.get_input.confirm_ask = True
main(
["--env-file", str(env_file_path), "--no-git", "--exit"],
input=DummyInput(),
output=DummyOutput(),
)
MockInputOutput.assert_called_once()
# Check if the color settings are for dark mode
_, kwargs = MockInputOutput.call_args
self.assertEqual(kwargs["code_theme"], "monokai")
def test_default_env_file_sets_automatic_variable(self):
self.create_env_file(".env", "AIDER_DARK_MODE=True")
with patch("aider.main.InputOutput") as MockInputOutput:
MockInputOutput.return_value.get_input.return_value = None
MockInputOutput.return_value.get_input.confirm_ask = True
main(["--no-git", "--exit"], input=DummyInput(), output=DummyOutput())
# Ensure InputOutput was called
MockInputOutput.assert_called_once()
# Check if the color settings are for dark mode
_, kwargs = MockInputOutput.call_args
self.assertEqual(kwargs["code_theme"], "monokai")
def test_false_vals_in_env_file(self):
self.create_env_file(".env", "AIDER_SHOW_DIFFS=off")
with patch("aider.coders.Coder.create") as MockCoder:
main(["--no-git", "--yes"], input=DummyInput(), output=DummyOutput())
MockCoder.assert_called_once()
_, kwargs = MockCoder.call_args
self.assertEqual(kwargs["show_diffs"], False)
def test_true_vals_in_env_file(self):
self.create_env_file(".env", "AIDER_SHOW_DIFFS=on")
with patch("aider.coders.Coder.create") as MockCoder:
main(["--no-git", "--yes"], input=DummyInput(), output=DummyOutput())
MockCoder.assert_called_once()
_, kwargs = MockCoder.call_args
self.assertEqual(kwargs["show_diffs"], True)
def test_lint_option(self):
with GitTemporaryDirectory() as git_dir:
# Create a dirty file in the root
dirty_file = Path("dirty_file.py")
dirty_file.write_text("def foo():\n return 'bar'")
repo = git.Repo(".")
repo.git.add(str(dirty_file))
repo.git.commit("-m", "new")
dirty_file.write_text("def foo():\n return '!!!!!'")
# Create a subdirectory
subdir = Path(git_dir) / "subdir"
subdir.mkdir()
# Change to the subdirectory
os.chdir(subdir)
# Mock the Linter class
with patch("aider.linter.Linter.lint") as MockLinter:
MockLinter.return_value = ""
# Run main with --lint option
main(["--lint", "--yes"])
# Check if the Linter was called with a filename ending in "dirty_file.py"
# but not ending in "subdir/dirty_file.py"
MockLinter.assert_called_once()
called_arg = MockLinter.call_args[0][0]
self.assertTrue(called_arg.endswith("dirty_file.py"))
self.assertFalse(called_arg.endswith(f"subdir{os.path.sep}dirty_file.py"))
def test_verbose_mode_lists_env_vars(self):
self.create_env_file(".env", "AIDER_DARK_MODE=on")
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
main(
["--no-git", "--verbose", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
)
output = mock_stdout.getvalue()
relevant_output = "\n".join(
line
for line in output.splitlines()
if "AIDER_DARK_MODE" in line or "dark_mode" in line
) # this bit just helps failing assertions to be easier to read
self.assertIn("AIDER_DARK_MODE", relevant_output)
self.assertIn("dark_mode", relevant_output)
self.assertRegex(relevant_output, r"AIDER_DARK_MODE:\s+on")
self.assertRegex(relevant_output, r"dark_mode:\s+True")
def test_yaml_config_file_loading(self):
with GitTemporaryDirectory() as git_dir:
git_dir = Path(git_dir)
# Create fake home directory
fake_home = git_dir / "fake_home"
fake_home.mkdir()
os.environ["HOME"] = str(fake_home)
# Create subdirectory as current working directory
cwd = git_dir / "subdir"
cwd.mkdir()
os.chdir(cwd)
# Create .aider.conf.yml files in different locations
home_config = fake_home / ".aider.conf.yml"
git_config = git_dir / ".aider.conf.yml"
cwd_config = cwd / ".aider.conf.yml"
named_config = git_dir / "named.aider.conf.yml"
cwd_config.write_text("model: gpt-4-32k\nmap-tokens: 4096\n")
git_config.write_text("model: gpt-4\nmap-tokens: 2048\n")
home_config.write_text("model: gpt-3.5-turbo\nmap-tokens: 1024\n")
named_config.write_text("model: gpt-4-1106-preview\nmap-tokens: 8192\n")
with (
patch("pathlib.Path.home", return_value=fake_home),
patch("aider.coders.Coder.create") as MockCoder,
):
# Test loading from specified config file
main(
["--yes", "--exit", "--config", str(named_config)],
input=DummyInput(),
output=DummyOutput(),
)
_, kwargs = MockCoder.call_args
self.assertEqual(kwargs["main_model"].name, "gpt-4-1106-preview")
self.assertEqual(kwargs["map_tokens"], 8192)
# Test loading from current working directory
main(["--yes", "--exit"], input=DummyInput(), output=DummyOutput())
_, kwargs = MockCoder.call_args
print("kwargs:", kwargs) # Add this line for debugging
self.assertIn("main_model", kwargs, "main_model key not found in kwargs")
self.assertEqual(kwargs["main_model"].name, "gpt-4-32k")
self.assertEqual(kwargs["map_tokens"], 4096)
# Test loading from git root
cwd_config.unlink()
main(["--yes", "--exit"], input=DummyInput(), output=DummyOutput())
_, kwargs = MockCoder.call_args
self.assertEqual(kwargs["main_model"].name, "gpt-4")
self.assertEqual(kwargs["map_tokens"], 2048)
# Test loading from home directory
git_config.unlink()
main(["--yes", "--exit"], input=DummyInput(), output=DummyOutput())
_, kwargs = MockCoder.call_args
self.assertEqual(kwargs["main_model"].name, "gpt-3.5-turbo")
self.assertEqual(kwargs["map_tokens"], 1024)
def test_map_tokens_option(self):
with GitTemporaryDirectory():
with patch("aider.coders.base_coder.RepoMap") as MockRepoMap:
MockRepoMap.return_value.max_map_tokens = 0
main(
["--model", "gpt-4", "--map-tokens", "0", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
)
MockRepoMap.assert_not_called()
def test_map_tokens_option_with_non_zero_value(self):
with GitTemporaryDirectory():
with patch("aider.coders.base_coder.RepoMap") as MockRepoMap:
MockRepoMap.return_value.max_map_tokens = 1000
main(
["--model", "gpt-4", "--map-tokens", "1000", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
)
MockRepoMap.assert_called_once()
def test_read_option(self):
with GitTemporaryDirectory():
test_file = "test_file.txt"
Path(test_file).touch()
coder = main(
["--read", test_file, "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertIn(str(Path(test_file).resolve()), coder.abs_read_only_fnames)
def test_read_option_with_external_file(self):
with tempfile.NamedTemporaryFile(mode="w", delete=False) as external_file:
external_file.write("External file content")
external_file_path = external_file.name
try:
with GitTemporaryDirectory():
coder = main(
["--read", external_file_path, "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
real_external_file_path = os.path.realpath(external_file_path)
self.assertIn(real_external_file_path, coder.abs_read_only_fnames)
finally:
os.unlink(external_file_path)
def test_model_metadata_file(self):
# Re-init so we don't have old data lying around from earlier test cases
from aider import models
models.model_info_manager = models.ModelInfoManager()
from aider.llm import litellm
litellm._lazy_module = None
with GitTemporaryDirectory():
metadata_file = Path(".aider.model.metadata.json")
# must be a fully qualified model name: provider/...
metadata_content = {"deepseek/deepseek-chat": {"max_input_tokens": 1234}}
metadata_file.write_text(json.dumps(metadata_content))
coder = main(
[
"--model",
"deepseek/deepseek-chat",
"--model-metadata-file",
str(metadata_file),
"--exit",
"--yes",
],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertEqual(coder.main_model.info["max_input_tokens"], 1234)
def test_sonnet_and_cache_options(self):
with GitTemporaryDirectory():
with patch("aider.coders.base_coder.RepoMap") as MockRepoMap:
mock_repo_map = MagicMock()
mock_repo_map.max_map_tokens = 1000 # Set a specific value
MockRepoMap.return_value = mock_repo_map
main(
["--sonnet", "--cache-prompts", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
)
MockRepoMap.assert_called_once()
call_args, call_kwargs = MockRepoMap.call_args
self.assertEqual(
call_kwargs.get("refresh"), "files"
) # Check the 'refresh' keyword argument
def test_sonnet_and_cache_prompts_options(self):
with GitTemporaryDirectory():
coder = main(
["--sonnet", "--cache-prompts", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertTrue(coder.add_cache_headers)
def test_4o_and_cache_options(self):
with GitTemporaryDirectory():
coder = main(
["--4o", "--cache-prompts", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertFalse(coder.add_cache_headers)
def test_return_coder(self):
with GitTemporaryDirectory():
result = main(
["--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertIsInstance(result, Coder)
result = main(
["--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=False,
)
self.assertIsNone(result)
def test_map_mul_option(self):
with GitTemporaryDirectory():
coder = main(
["--map-mul", "5", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertIsInstance(coder, Coder)
self.assertEqual(coder.repo_map.map_mul_no_files, 5)
def test_suggest_shell_commands_default(self):
with GitTemporaryDirectory():
coder = main(
["--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertTrue(coder.suggest_shell_commands)
def test_suggest_shell_commands_disabled(self):
with GitTemporaryDirectory():
coder = main(
["--no-suggest-shell-commands", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertFalse(coder.suggest_shell_commands)
def test_suggest_shell_commands_enabled(self):
with GitTemporaryDirectory():
coder = main(
["--suggest-shell-commands", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertTrue(coder.suggest_shell_commands)
def test_detect_urls_default(self):
with GitTemporaryDirectory():
coder = main(
["--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertTrue(coder.detect_urls)
def test_detect_urls_disabled(self):
with GitTemporaryDirectory():
coder = main(
["--no-detect-urls", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertFalse(coder.detect_urls)
def test_detect_urls_enabled(self):
with GitTemporaryDirectory():
coder = main(
["--detect-urls", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
return_coder=True,
)
self.assertTrue(coder.detect_urls)
def test_accepts_settings_warnings(self):
# Test that appropriate warnings are shown based on accepts_settings configuration
with GitTemporaryDirectory():
# Test model that accepts the thinking_tokens setting
with (
patch("aider.io.InputOutput.tool_warning") as mock_warning,
patch("aider.models.Model.set_thinking_tokens") as mock_set_thinking,
):
main(
[
"--model",
"anthropic/claude-3-7-sonnet-20250219",
"--thinking-tokens",
"1000",
"--yes",
"--exit",
],
input=DummyInput(),
output=DummyOutput(),
)
# No warning should be shown as this model accepts thinking_tokens
for call in mock_warning.call_args_list:
self.assertNotIn("thinking_tokens", call[0][0])
# Method should be called
mock_set_thinking.assert_called_once_with("1000")
# Test model that doesn't have accepts_settings for thinking_tokens
with (
patch("aider.io.InputOutput.tool_warning") as mock_warning,
patch("aider.models.Model.set_thinking_tokens") as mock_set_thinking,
):
main(
[
"--model",
"gpt-4o",
"--thinking-tokens",
"1000",
"--check-model-accepts-settings",
"--yes",
"--exit",
],
input=DummyInput(),
output=DummyOutput(),
)
# Warning should be shown
warning_shown = False
for call in mock_warning.call_args_list:
if "thinking_tokens" in call[0][0]:
warning_shown = True
self.assertTrue(warning_shown)
# Method should NOT be called because model doesn't support it and check flag is on
mock_set_thinking.assert_not_called()
# Test model that accepts the reasoning_effort setting
with (
patch("aider.io.InputOutput.tool_warning") as mock_warning,
patch("aider.models.Model.set_reasoning_effort") as mock_set_reasoning,
):
main(
["--model", "o1", "--reasoning-effort", "3", "--yes", "--exit"],
input=DummyInput(),
output=DummyOutput(),
)
# No warning should be shown as this model accepts reasoning_effort
for call in mock_warning.call_args_list:
self.assertNotIn("reasoning_effort", call[0][0])
# Method should be called
mock_set_reasoning.assert_called_once_with("3")
# Test model that doesn't have accepts_settings for reasoning_effort
with (
patch("aider.io.InputOutput.tool_warning") as mock_warning,
patch("aider.models.Model.set_reasoning_effort") as mock_set_reasoning,
):
main(
["--model", "gpt-3.5-turbo", "--reasoning-effort", "3", "--yes", "--exit"],
input=DummyInput(),
output=DummyOutput(),
)
# Warning should be shown
warning_shown = False
for call in mock_warning.call_args_list:
if "reasoning_effort" in call[0][0]:
warning_shown = True
self.assertTrue(warning_shown)
# Method should still be called by default
mock_set_reasoning.assert_not_called()
@patch("aider.models.ModelInfoManager.set_verify_ssl")
def test_no_verify_ssl_sets_model_info_manager(self, mock_set_verify_ssl):
with GitTemporaryDirectory():
# Mock Model class to avoid actual model initialization
with patch("aider.models.Model") as mock_model:
# Configure the mock to avoid the TypeError
mock_model.return_value.info = {}
mock_model.return_value.name = "gpt-4" # Add a string name
mock_model.return_value.validate_environment.return_value = {
"missing_keys": [],
"keys_in_environment": [],
}
# Mock fuzzy_match_models to avoid string operations on MagicMock
with patch("aider.models.fuzzy_match_models", return_value=[]):
main(
["--no-verify-ssl", "--exit", "--yes"],
input=DummyInput(),
output=DummyOutput(),
)
mock_set_verify_ssl.assert_called_once_with(False)
def test_pytest_env_vars(self):
# Verify that environment variables from pytest.ini are properly set
self.assertEqual(os.environ.get("AIDER_ANALYTICS"), "false")
def test_set_env_single(self):
# Test setting a single environment variable
with GitTemporaryDirectory():
main(["--set-env", "TEST_VAR=test_value", "--exit", "--yes"])
self.assertEqual(os.environ.get("TEST_VAR"), "test_value")
def test_set_env_multiple(self):
# Test setting multiple environment variables
with GitTemporaryDirectory():
main(
[
"--set-env",
"TEST_VAR1=value1",
"--set-env",
"TEST_VAR2=value2",
"--exit",
"--yes",
]
)
self.assertEqual(os.environ.get("TEST_VAR1"), "value1")
self.assertEqual(os.environ.get("TEST_VAR2"), "value2")
def test_set_env_with_spaces(self):
# Test setting env var with spaces in value
with GitTemporaryDirectory():
main(["--set-env", "TEST_VAR=test value with spaces", "--exit", "--yes"])
self.assertEqual(os.environ.get("TEST_VAR"), "test value with spaces")
def test_set_env_invalid_format(self):
# Test invalid format handling
with GitTemporaryDirectory():
result = main(["--set-env", "INVALID_FORMAT", "--exit", "--yes"])
self.assertEqual(result, 1)
def test_api_key_single(self):
# Test setting a single API key
with GitTemporaryDirectory():
main(["--api-key", "anthropic=test-key", "--exit", "--yes"])
self.assertEqual(os.environ.get("ANTHROPIC_API_KEY"), "test-key")
def test_api_key_multiple(self):
# Test setting multiple API keys
with GitTemporaryDirectory():
main(["--api-key", "anthropic=key1", "--api-key", "openai=key2", "--exit", "--yes"])
self.assertEqual(os.environ.get("ANTHROPIC_API_KEY"), "key1")
self.assertEqual(os.environ.get("OPENAI_API_KEY"), "key2")
def test_api_key_invalid_format(self):
# Test invalid format handling
with GitTemporaryDirectory():
result = main(["--api-key", "INVALID_FORMAT", "--exit", "--yes"])
self.assertEqual(result, 1)
def test_git_config_include(self):
# Test that aider respects git config includes for user.name and user.email
with GitTemporaryDirectory() as git_dir:
git_dir = Path(git_dir)
# Create an includable config file with user settings
include_config = git_dir / "included.gitconfig"
include_config.write_text(
"[user]\n name = Included User\n email = included@example.com\n"
)
# Set up main git config to include the other file
repo = git.Repo(git_dir)
include_path = str(include_config).replace("\\", "/")
repo.git.config("--local", "include.path", str(include_path))
# Verify the config is set up correctly using git command
self.assertEqual(repo.git.config("user.name"), "Included User")
self.assertEqual(repo.git.config("user.email"), "included@example.com")
# Manually check the git config file to confirm include directive
git_config_path = git_dir / ".git" / "config"
git_config_content = git_config_path.read_text()
# Run aider and verify it doesn't change the git config
main(["--yes", "--exit"], input=DummyInput(), output=DummyOutput())