-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathtest_code_generator_main.py
More file actions
2367 lines (1995 loc) · 92.6 KB
/
test_code_generator_main.py
File metadata and controls
2367 lines (1995 loc) · 92.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 asyncio
import json
import os
import pathlib
import shlex
import subprocess
import sys
import types
import pytest
from unittest.mock import MagicMock, patch, mock_open, AsyncMock
import click
import requests
from rich.panel import Panel
from rich.text import Text # ADDED THIS IMPORT
# Import the function to be tested using an absolute path
from pdd.code_generator_main import code_generator_main, CLOUD_REQUEST_TIMEOUT
from pdd.core.cloud import CloudConfig
from pdd.get_jwt_token import AuthError, NetworkError, TokenError, UserCancelledError, RateLimitError
# Get the cloud URL for assertions in tests
CLOUD_GENERATE_URL = CloudConfig.get_endpoint_url("generateCode")
from pdd import DEFAULT_TIME # Ensure DEFAULT_TIME is available if mock_ctx doesn't always set 'time'
# Constants for mocking
DEFAULT_MOCK_GENERATED_CODE = "def hello():\n print('Hello, world!')"
DEFAULT_MOCK_COST = 0.001
DEFAULT_MOCK_MODEL_NAME = "mock_model_v1"
DEFAULT_MOCK_LANGUAGE = "python"
# Test Plan
#
# I. Setup and Mocking (Fixtures)
# 1. `mock_ctx`: Pytest fixture for `click.Context`.
# 2. `temp_dir_setup`: Pytest fixture to create temporary directories for prompts, output. Manages cleanup.
# 3. `git_repo_setup`: Pytest fixture to initialize a temporary git repository, commit files, and provide paths.
# 4. `mock_env_vars`: Pytest fixture using `monkeypatch` to set/unset environment variables.
# 5. `mock_construct_paths_fixture`: Autouse fixture to mock `pdd.construct_paths.construct_paths`.
# 6. `mock_pdd_preprocess_fixture`: Autouse fixture to mock `pdd.preprocess.preprocess`.
# 7. `mock_local_generator_fixture`: Autouse fixture to mock `pdd.code_generator.local_code_generator_func`.
# 8. `mock_incremental_generator_fixture`: Autouse fixture to mock `pdd.incremental_code_generator.incremental_code_generator_func`.
# 9. `mock_get_jwt_token_fixture`: Autouse fixture to mock `pdd.get_jwt_token.get_jwt_token`.
# 10. `mock_requests_post_fixture`: Autouse fixture to mock `requests.post`.
# 11. `mock_subprocess_run_fixture`: Autouse fixture to mock `subprocess.run`.
# 12. `mock_rich_console_fixture`: Autouse fixture to mock `Console.print`.
#
# II. Core Functionality Tests
#
# A. Full Generation - Local Execution
# 1. `test_full_gen_local_no_output_file`: Prompt exists, no output file yet. `--local` is True.
# 2. `test_full_gen_local_output_exists_no_incremental_possible`: Prompt exists, output file exists, but no original prompt source. `--local` is True.
# 3. `test_full_gen_local_output_to_console`: Prompt exists, no output path specified. `--local` is True, `quiet=False`.
#
# B. Full Generation - Cloud Execution
# 1. `test_full_gen_cloud_success`: Prompt exists, no output file. `--local` is False. `get_jwt_token` and `requests.post` succeed.
# 2. `test_full_gen_cloud_auth_failure_fallback_to_local`: `--local` is False. `get_jwt_token` raises `AuthError`.
# 3. `test_full_gen_cloud_network_timeout_fallback_to_local`: `--local` is False. `requests.post` raises `requests.exceptions.Timeout`.
# 4. `test_full_gen_cloud_http_error_fallback_to_local`: `--local` is False. `requests.post` raises `requests.exceptions.HTTPError`.
# 5. `test_full_gen_cloud_json_error_fallback_to_local`: `--local` is False. `requests.post` returns non-JSON response.
# 6. `test_full_gen_cloud_no_code_returned_fallback_to_local`: `--local` is False. `requests.post` succeeds but JSON response has no `generatedCode`.
# 7. `test_full_gen_cloud_missing_env_vars_fallback_to_local`: `--local` is False. Firebase/GitHub env vars not set.
#
# C. Incremental Generation
# 1. `test_incremental_gen_with_original_prompt_file`: Prompt, output, and original_prompt_file exist. `incremental_code_generator_func` returns `is_incremental=True`.
# 2. `test_incremental_gen_with_git_committed_prompt`: Prompt in git, modified. Output file exists. `incremental_code_generator_func` returns `is_incremental=True`.
# 3. `test_incremental_gen_git_staging_untracked_files`: Prompt is untracked, output file exists. Incremental attempt. `git_add_files` called.
# 4. `test_incremental_gen_git_staging_modified_files`: Prompt is committed and modified, output file exists. Incremental attempt. `git_add_files` called.
# 5. `test_incremental_gen_fallback_to_full_on_generator_suggestion`: Conditions for incremental met. `incremental_code_generator_func` returns `is_incremental=False`.
# 6. `test_incremental_gen_force_incremental_flag_success`: Conditions for incremental met. `force_incremental_flag=True`.
# 7. `test_incremental_gen_force_incremental_flag_but_no_output_file`: `force_incremental_flag=True`, but no output file. Warns, does full.
# 8. `test_incremental_gen_force_incremental_flag_but_no_original_prompt`: `force_incremental_flag=True`, output file exists, but no original prompt source. Warns, does full.
# 9. `test_incremental_gen_no_git_repo_fallback_to_full_if_git_needed`: Output file exists, prompt not in git, no `original_prompt_file` specified. Full generation.
#
# D. File and Path Handling
# 1. `test_error_prompt_file_not_found`: `prompt_file` path is invalid.
# 2. `test_error_original_prompt_file_not_found`: `original_prompt_file_path` is invalid.
# 3. `test_output_file_creation_and_overwrite`: Test with and without `force=True` when output file exists.
#
# E. Error and Edge Cases
# 1. `test_code_generation_fails_no_code_produced`: Generator returns `None` for code.
# 2. `test_unexpected_exception_during_generation`: Generator raises a generic `Exception`.
#
# III. Git Helper Function Tests (Simplified for brevity, focusing on `code_generator_main`'s usage)
# * Git helper tests are implicitly covered by the incremental generation tests that rely on mocked `subprocess.run`.
# Dedicated tests for git helpers would mock `subprocess.run` and assert behavior of `is_git_repository`,
# `get_git_committed_content`, `get_file_git_status`, `git_add_files`.
# For this test suite, we focus on `code_generator_main`'s integration of these.
@pytest.fixture
def mock_ctx(monkeypatch):
ctx = MagicMock(spec=click.Context)
ctx.obj = {
'local': False,
'strength': 0.5,
'temperature': 0.0,
'time': 0.25,
'verbose': False,
'force': False,
'quiet': False,
}
return ctx
@pytest.fixture
def temp_dir_setup(tmp_path, monkeypatch):
output_dir = tmp_path / "output"
output_dir.mkdir(exist_ok=True)
prompts_dir = tmp_path / "prompts"
prompts_dir.mkdir(exist_ok=True)
# Create a dummy PDD_PATH/data for construct_paths if it relies on it
pdd_path_data = tmp_path / "pdd_root" / "data"
pdd_path_data.mkdir(parents=True, exist_ok=True)
(pdd_path_data / "llm_model.csv").write_text("model,cost\nmock,0.01") # Dummy content
monkeypatch.setenv("PDD_PATH", str(tmp_path / "pdd_root"))
return {"output_dir": output_dir, "prompts_dir": prompts_dir, "tmp_path": tmp_path}
@pytest.fixture
def git_repo_setup(temp_dir_setup, monkeypatch):
git_dir = temp_dir_setup["tmp_path"] / "git_repo"
git_dir.mkdir()
original_subprocess_run = subprocess.run
def mock_git_run_for_setup(*args, **kwargs):
cmd = args[0]
cwd_resolved = pathlib.Path(kwargs.get("cwd", str(git_dir))).resolve()
git_dir_resolved = git_dir.resolve()
if cmd[0] == "git":
if cmd[1] == "rev-parse" and "--is-inside-work-tree" in cmd:
if (git_dir_resolved / ".git").exists() and \
(cwd_resolved == git_dir_resolved or str(git_dir_resolved) in str(cwd_resolved)):
return subprocess.CompletedProcess(args, 0, stdout="true", stderr="")
return subprocess.CompletedProcess(args, 0, stdout="false", stderr="")
if cmd[1] == "rev-parse" and "--show-toplevel" in cmd:
if (git_dir_resolved / ".git").exists() and \
(cwd_resolved == git_dir_resolved or str(git_dir_resolved) in str(cwd_resolved)):
return subprocess.CompletedProcess(args, 0, stdout=str(git_dir_resolved), stderr="")
return subprocess.CompletedProcess(args, 128, stdout="", stderr="Not a git repository")
return original_subprocess_run(*args, **kwargs)
monkeypatch.setattr(subprocess, 'run', mock_git_run_for_setup)
(git_dir / ".git").mkdir()
return git_dir
# --- Start Mocks for PDD internal functions ---
@pytest.fixture
def mock_construct_paths_fixture(monkeypatch):
mock = MagicMock()
monkeypatch.setattr("pdd.code_generator_main.construct_paths", mock)
mock.return_value = (
{},
{"prompt_file": "Test prompt content"},
{"output": "output/test_output.py"},
DEFAULT_MOCK_LANGUAGE
)
return mock
@pytest.fixture
def mock_pdd_preprocess_fixture(monkeypatch):
# Default mock returns the input unchanged to allow tests to assert substitution behavior when needed
def passthrough(prompt_text, recursive=False, double_curly_brackets=True, exclude_keys=None):
return prompt_text
mock = MagicMock(side_effect=passthrough)
monkeypatch.setattr("pdd.code_generator_main.pdd_preprocess", mock)
return mock
@pytest.fixture
def mock_local_generator_fixture(monkeypatch):
mock = MagicMock(return_value=(DEFAULT_MOCK_GENERATED_CODE, DEFAULT_MOCK_COST, DEFAULT_MOCK_MODEL_NAME))
monkeypatch.setattr("pdd.code_generator_main.local_code_generator_func", mock)
return mock
@pytest.fixture
def mock_incremental_generator_fixture(monkeypatch):
mock = MagicMock(return_value=(DEFAULT_MOCK_GENERATED_CODE, True, DEFAULT_MOCK_COST, DEFAULT_MOCK_MODEL_NAME))
monkeypatch.setattr("pdd.code_generator_main.incremental_code_generator_func", mock)
return mock
# --- End Mocks for PDD internal functions ---
# --- Start Mocks for External Dependencies ---
@pytest.fixture(autouse=True)
def mock_get_jwt_token_fixture(monkeypatch):
# Mock CloudConfig.get_jwt_token since we no longer import get_jwt_token directly
mock = MagicMock(return_value="test_jwt_token")
monkeypatch.setattr("pdd.code_generator_main.CloudConfig.get_jwt_token", mock)
return mock
@pytest.fixture(autouse=True)
def mock_requests_post_fixture(monkeypatch):
mock = MagicMock()
mock_response = MagicMock(spec=requests.Response)
mock_response.json.return_value = {"generatedCode": DEFAULT_MOCK_GENERATED_CODE, "totalCost": DEFAULT_MOCK_COST, "modelName": "cloud_model"}
mock_response.status_code = 200
mock_response.raise_for_status = MagicMock()
mock.return_value = mock_response
monkeypatch.setattr("pdd.code_generator_main.requests.post", mock)
return mock
@pytest.fixture(autouse=True)
def mock_subprocess_run_fixture(monkeypatch):
original_run = subprocess.run
mock = MagicMock(return_value=subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr=""))
mock.original_run = original_run
monkeypatch.setattr("pdd.code_generator_main.subprocess.run", mock)
monkeypatch.setattr(subprocess, "run", mock)
return mock
@pytest.fixture(autouse=True)
def mock_rich_console_fixture(monkeypatch):
mock_console_print = MagicMock()
monkeypatch.setattr("pdd.code_generator_main.console.print", mock_console_print)
return mock_console_print
@pytest.fixture
def mock_env_vars(monkeypatch):
monkeypatch.setenv("NEXT_PUBLIC_FIREBASE_API_KEY", "test_firebase_key")
monkeypatch.setenv("GITHUB_CLIENT_ID", "test_github_id")
# --- Helper to create files ---
def create_file(path, content=""):
pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True)
pathlib.Path(path).write_text(content, encoding="utf-8")
# === Test Cases ===
# A. Full Generation - Local Execution
def test_full_gen_local_no_output_file(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_local_generator_fixture, mock_env_vars
):
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "test_prompt_python.prompt"
create_file(prompt_file_path, "Local test prompt")
output_file_name = "local_output.py"
output_file_path_str = str(temp_dir_setup["output_dir"] / output_file_name)
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Local test prompt"},
{"output": output_file_path_str},
"python"
)
code, incremental, cost, model = code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
assert code == DEFAULT_MOCK_GENERATED_CODE
assert not incremental
assert cost == DEFAULT_MOCK_COST
assert model == DEFAULT_MOCK_MODEL_NAME
# Do not assert preprocess_prompt flag here because wrapper may pre-process before calling generator
called_kwargs = mock_local_generator_fixture.call_args.kwargs
assert called_kwargs["language"] == "python"
assert called_kwargs["strength"] == mock_ctx.obj['strength']
assert called_kwargs["temperature"] == mock_ctx.obj['temperature']
assert called_kwargs["time"] == mock_ctx.obj['time']
assert called_kwargs["verbose"] == mock_ctx.obj['verbose']
assert called_kwargs["output_schema"] is None
assert (temp_dir_setup["output_dir"] / output_file_name).exists()
assert (temp_dir_setup["output_dir"] / output_file_name).read_text() == DEFAULT_MOCK_GENERATED_CODE
def test_preprocess_order_local_flow(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_local_generator_fixture, mock_pdd_preprocess_fixture, mock_env_vars
):
"""Ensure local path calls preprocess twice: includes-first then double-curly."""
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "order_prompt_python.prompt"
create_file(prompt_file_path, "Hello $NAME")
output_file_path_str = str(temp_dir_setup["output_dir"] / "order.py")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Hello $NAME"},
{"output": output_file_path_str},
"python"
)
code_generator_main(mock_ctx, str(prompt_file_path), output_file_path_str, None, False, env_vars={"NAME": "X"})
# Expect two preprocess calls in order
calls = mock_pdd_preprocess_fixture.call_args_list
assert len(calls) >= 2
# First call: recursive=True, double_curly=False
args, kwargs = calls[0]
assert kwargs.get('recursive') is True
assert kwargs.get('double_curly_brackets') is False
# Second call: recursive=False, double_curly=True
args2, kwargs2 = calls[1]
assert kwargs2.get('recursive') is False
assert kwargs2.get('double_curly_brackets') is True
def test_full_gen_local_output_exists_no_incremental_possible(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_local_generator_fixture, mock_subprocess_run_fixture, mock_env_vars
):
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "test_prompt_python.prompt"
create_file(prompt_file_path, "Local test prompt")
output_file_name = "existing_local_output.py"
output_file_path = temp_dir_setup["output_dir"] / output_file_name
create_file(output_file_path, "Old code")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Local test prompt"},
{"output": str(output_file_path)},
"python"
)
with patch("pdd.code_generator_main.is_git_repository", return_value=False):
code, _, _, _ = code_generator_main(
mock_ctx, str(prompt_file_path), str(output_file_path), None, False
)
assert code == DEFAULT_MOCK_GENERATED_CODE
called_kwargs = mock_local_generator_fixture.call_args.kwargs
assert called_kwargs["language"] == "python"
assert called_kwargs["strength"] == mock_ctx.obj['strength']
assert called_kwargs["temperature"] == mock_ctx.obj['temperature']
assert called_kwargs["time"] == mock_ctx.obj['time']
assert called_kwargs["verbose"] == mock_ctx.obj['verbose']
assert called_kwargs["output_schema"] is None
assert output_file_path.read_text() == DEFAULT_MOCK_GENERATED_CODE
def test_env_substitution_in_output_path_and_prompt(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_local_generator_fixture, monkeypatch, mock_env_vars
):
"""Ensure $KEY and ${KEY} are substituted using env_vars for prompt and output path."""
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "env_sub_prompt_python.prompt"
prompt_content = "Hello $NAME and ${ITEM} and $UNKNOWN"
create_file(prompt_file_path, prompt_content)
output_dir = temp_dir_setup["output_dir"]
output_pattern = str(output_dir / "${NAME}.txt")
# Construct paths should return our provided strings
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": prompt_content},
{"output": output_pattern},
"python",
)
# Run with env_vars passed directly
code, incremental, cost, model = code_generator_main(
mock_ctx,
str(prompt_file_path),
output_pattern,
None,
False,
env_vars={"NAME": "Alice", "ITEM": "Book"},
)
# Local generator should be called with substituted prompt (UNKNOWN remains)
called_kwargs = mock_local_generator_fixture.call_args.kwargs
assert "Hello Alice and Book and $UNKNOWN" in called_kwargs["prompt"]
# Output should be written to expanded path
expanded = output_dir / "Alice.txt"
assert expanded.exists(), f"Expected output file at {expanded}"
def test_full_gen_local_output_to_console(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_local_generator_fixture, mock_rich_console_fixture, mock_env_vars
):
mock_ctx.obj['local'] = True
mock_ctx.obj['quiet'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "test_prompt_python.prompt"
create_file(prompt_file_path, "Console test prompt")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Console test prompt"},
{"output": None},
"python"
)
code, _, _, _ = code_generator_main(
mock_ctx, str(prompt_file_path), None, None, False
)
assert code == DEFAULT_MOCK_GENERATED_CODE
called_kwargs = mock_local_generator_fixture.call_args.kwargs
assert called_kwargs["language"] == "python"
assert called_kwargs["strength"] == mock_ctx.obj['strength']
assert called_kwargs["temperature"] == mock_ctx.obj['temperature']
assert called_kwargs["time"] == mock_ctx.obj['time']
assert called_kwargs["verbose"] == mock_ctx.obj['verbose']
assert called_kwargs["output_schema"] is None
printed_to_console = False
for call_args in mock_rich_console_fixture.call_args_list:
args, _ = call_args
if args and isinstance(args[0], Panel):
panel_obj = args[0]
if hasattr(panel_obj, 'renderable') and isinstance(panel_obj.renderable, Text):
if DEFAULT_MOCK_GENERATED_CODE in panel_obj.renderable.plain:
printed_to_console = True
break
assert printed_to_console
# B. Full Generation - Cloud Execution
def test_full_gen_cloud_success(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_pdd_preprocess_fixture,
mock_get_jwt_token_fixture, mock_requests_post_fixture, mock_env_vars
):
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "cloud_prompt_python.prompt"
create_file(prompt_file_path, "Cloud test prompt")
output_file_name = "cloud_output.py"
output_file_path_str = str(temp_dir_setup["output_dir"] / output_file_name)
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Cloud test prompt"},
{"output": output_file_path_str},
"python"
)
mock_pdd_preprocess_fixture.return_value = "Preprocessed cloud prompt"
code, incremental, cost, model = code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
assert code == DEFAULT_MOCK_GENERATED_CODE
assert not incremental
assert cost == DEFAULT_MOCK_COST
assert model == "cloud_model"
# Wrapper now preprocesses twice: includes (no doubling), then doubling
calls = mock_pdd_preprocess_fixture.call_args_list
assert len(calls) == 2
_args1, kwargs1 = calls[0]
assert kwargs1.get('recursive') is True
assert kwargs1.get('double_curly_brackets') is False
_args2, kwargs2 = calls[1]
assert kwargs2.get('recursive') is False
assert kwargs2.get('double_curly_brackets') is True
mock_get_jwt_token_fixture.assert_called_once()
mock_requests_post_fixture.assert_called_once_with(
CLOUD_GENERATE_URL,
json={
# With the default passthrough side_effect, promptContent remains original
"promptContent": "Cloud test prompt",
"language": "python",
"strength": mock_ctx.obj['strength'],
"temperature": mock_ctx.obj['temperature'],
"verbose": mock_ctx.obj['verbose']
},
headers={"Authorization": "Bearer test_jwt_token", "Content-Type": "application/json"},
timeout=CLOUD_REQUEST_TIMEOUT
)
assert (temp_dir_setup["output_dir"] / output_file_name).exists()
# Tests for JSON fence stripping from cloud responses
@pytest.mark.parametrize("fenced_code,expected_output", [
('```json\n{"key": "value"}\n```', '{"key": "value"}'),
('```\n{"key": "value"}\n```', '{"key": "value"}'),
('```json\n\n{"nested": {"a": 1}}\n\n```', '{"nested": {"a": 1}}'),
('{"key": "value"}', '{"key": "value"}'), # No fences, unchanged
(' ```json\n{"key": "value"}\n``` ', '{"key": "value"}'), # With whitespace
])
def test_cloud_json_response_fence_stripping(
fenced_code, expected_output, mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture, mock_get_jwt_token_fixture, mock_requests_post_fixture, mock_env_vars
):
"""Test that markdown code fences are stripped from JSON responses in cloud mode."""
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "json_fence_prompt.prompt"
create_file(prompt_file_path, "Generate JSON")
output_file_name = "fence_output.json"
output_file_path_str = str(temp_dir_setup["output_dir"] / output_file_name)
mock_construct_paths_fixture.return_value = (
{},
{"prompt_file": "Generate JSON"},
{"output": output_file_path_str},
"json" # JSON language triggers fence stripping
)
mock_response = MagicMock(spec=requests.Response)
mock_response.json.return_value = {
"generatedCode": fenced_code,
"totalCost": 0.001,
"modelName": "cloud_model"
}
mock_response.status_code = 200
mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = mock_response
code, incremental, cost, model = code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
assert code == expected_output
assert not incremental
assert (temp_dir_setup["output_dir"] / output_file_name).exists()
assert (temp_dir_setup["output_dir"] / output_file_name).read_text() == expected_output
def test_cloud_non_json_response_not_stripped(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture, mock_get_jwt_token_fixture, mock_requests_post_fixture, mock_env_vars
):
"""Test that code fences are NOT stripped for non-JSON language responses."""
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "python_fence_prompt.prompt"
create_file(prompt_file_path, "Generate Python")
output_file_name = "fence_output.py"
output_file_path_str = str(temp_dir_setup["output_dir"] / output_file_name)
# Python code that happens to have backticks in it
python_code_with_backticks = '```python\ndef hello(): pass\n```'
mock_construct_paths_fixture.return_value = (
{},
{"prompt_file": "Generate Python"},
{"output": output_file_path_str},
"python" # Non-JSON language should NOT trigger fence stripping
)
mock_response = MagicMock(spec=requests.Response)
mock_response.json.return_value = {
"generatedCode": python_code_with_backticks,
"totalCost": 0.001,
"modelName": "cloud_model"
}
mock_response.status_code = 200
mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = mock_response
code, incremental, cost, model = code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
# For non-JSON, the code should remain unchanged (with fences)
assert code == python_code_with_backticks
assert (temp_dir_setup["output_dir"] / output_file_name).read_text() == python_code_with_backticks
def test_cloud_json_case_insensitive_language(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture, mock_get_jwt_token_fixture, mock_requests_post_fixture, mock_env_vars
):
"""Test that JSON fence stripping works with case-insensitive language check."""
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "json_case_prompt.prompt"
create_file(prompt_file_path, "Generate JSON")
output_file_name = "case_output.json"
output_file_path_str = str(temp_dir_setup["output_dir"] / output_file_name)
mock_construct_paths_fixture.return_value = (
{},
{"prompt_file": "Generate JSON"},
{"output": output_file_path_str},
"JSON" # Uppercase JSON
)
fenced_json = '```json\n{"test": true}\n```'
mock_response = MagicMock(spec=requests.Response)
mock_response.json.return_value = {
"generatedCode": fenced_json,
"totalCost": 0.001,
"modelName": "cloud_model"
}
mock_response.status_code = 200
mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = mock_response
code, incremental, cost, model = code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
assert code == '{"test": true}'
@pytest.mark.parametrize("cloud_error, local_fallback_expected", [
(AuthError("Auth failed"), True),
(requests.exceptions.Timeout("Timeout"), True),
(requests.exceptions.HTTPError(response=MagicMock(status_code=500, text="Server Error")), True),
(json.JSONDecodeError("msg", "doc", 0), True),
("NO_CODE_RETURNED", True),
])
def test_full_gen_cloud_fallback_scenarios(
cloud_error, local_fallback_expected, mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture, mock_get_jwt_token_fixture, mock_requests_post_fixture,
mock_local_generator_fixture, mock_rich_console_fixture, mock_env_vars
):
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "fallback_prompt_python.prompt"
create_file(prompt_file_path, "Fallback test prompt")
output_file_path_str = str(temp_dir_setup["output_dir"] / "fallback_output.py")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Fallback test prompt"},
{"output": output_file_path_str},
"python"
)
mock_pdd_preprocess_fixture.return_value = "Preprocessed fallback prompt"
if isinstance(cloud_error, AuthError):
# CloudConfig.get_jwt_token catches AuthError internally and returns None
mock_get_jwt_token_fixture.return_value = None
elif cloud_error == "NO_CODE_RETURNED":
mock_response = MagicMock(spec=requests.Response)
mock_response.json.return_value = {"totalCost": 0.01, "modelName": "cloud_model_no_code"}
mock_response.status_code = 200
mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = mock_response
mock_requests_post_fixture.side_effect = None
elif isinstance(cloud_error, json.JSONDecodeError):
mock_response = MagicMock(spec=requests.Response)
mock_response.json.side_effect = cloud_error
mock_response.status_code = 200
mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = mock_response
mock_requests_post_fixture.side_effect = None
else:
mock_requests_post_fixture.side_effect = cloud_error
mock_requests_post_fixture.return_value = None
if isinstance(cloud_error, requests.exceptions.HTTPError):
mock_requests_post_fixture.side_effect.response = cloud_error.response
code, _, _, _ = code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
if local_fallback_expected:
# Local fallback should call generator with preprocess_prompt=False (wrapper preprocessed already)
called_kwargs = mock_local_generator_fixture.call_args.kwargs
assert called_kwargs["prompt"] == "Fallback test prompt"
assert called_kwargs["language"] == "python"
assert called_kwargs["strength"] == mock_ctx.obj['strength']
assert called_kwargs["temperature"] == mock_ctx.obj['temperature']
assert called_kwargs["time"] == mock_ctx.obj['time']
assert called_kwargs["verbose"] == mock_ctx.obj['verbose']
assert called_kwargs["preprocess_prompt"] is False
assert called_kwargs["output_schema"] is None
assert code == DEFAULT_MOCK_GENERATED_CODE
assert any("falling back to local" in str(call_args[0][0]).lower() for call_args in mock_rich_console_fixture.call_args_list if call_args[0])
else:
mock_local_generator_fixture.assert_not_called()
mock_get_jwt_token_fixture.side_effect = None
mock_get_jwt_token_fixture.return_value = "test_jwt_token"
mock_requests_post_fixture.side_effect = None
default_mock_response = MagicMock(spec=requests.Response)
default_mock_response.json.return_value = {"generatedCode": DEFAULT_MOCK_GENERATED_CODE, "totalCost": DEFAULT_MOCK_COST, "modelName": "cloud_model"}
default_mock_response.status_code = 200
default_mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = default_mock_response
# Tests for non-recoverable HTTP errors that should NOT fall back to local
@pytest.mark.parametrize("status_code, error_message, expected_match", [
(402, "Insufficient credits", "Insufficient credits"),
(401, "Invalid token", "Cloud authentication failed"),
(403, "User not approved", "Access denied"),
(400, "Empty prompt not allowed", "Invalid request"),
])
def test_full_gen_cloud_non_recoverable_http_errors(
status_code, error_message, expected_match, mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture, mock_get_jwt_token_fixture, mock_requests_post_fixture,
mock_local_generator_fixture, mock_rich_console_fixture, mock_env_vars
):
"""Test that HTTP 402, 401, 403, 400 errors raise UsageError instead of falling back to local."""
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "non_recoverable_prompt_python.prompt"
create_file(prompt_file_path, "Non-recoverable test prompt")
output_file_path_str = str(temp_dir_setup["output_dir"] / "non_recoverable_output.py")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Non-recoverable test prompt"},
{"output": output_file_path_str},
"python"
)
mock_pdd_preprocess_fixture.return_value = "Preprocessed prompt"
# Create mock response with the specific status code
mock_response = MagicMock(spec=requests.Response)
mock_response.status_code = status_code
mock_response.text = error_message
mock_response.json.return_value = {"error": error_message, "currentBalance": 0, "estimatedCost": 0.05}
http_error = requests.exceptions.HTTPError(response=mock_response)
http_error.response = mock_response
mock_requests_post_fixture.side_effect = http_error
# Should raise click.UsageError, NOT fall back to local
with pytest.raises(click.UsageError, match=expected_match):
code_generator_main(
mock_ctx, str(prompt_file_path), output_file_path_str, None, False
)
# Local generator should NOT have been called
mock_local_generator_fixture.assert_not_called()
# Reset mocks for next test
mock_requests_post_fixture.side_effect = None
default_mock_response = MagicMock(spec=requests.Response)
default_mock_response.json.return_value = {"generatedCode": DEFAULT_MOCK_GENERATED_CODE, "totalCost": DEFAULT_MOCK_COST, "modelName": "cloud_model"}
default_mock_response.status_code = 200
default_mock_response.raise_for_status = MagicMock()
mock_requests_post_fixture.return_value = default_mock_response
def test_full_gen_cloud_insufficient_credits_displays_balance(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture, mock_get_jwt_token_fixture, mock_requests_post_fixture,
mock_local_generator_fixture, mock_rich_console_fixture, mock_env_vars
):
"""Test that HTTP 402 error displays current balance and estimated cost from response."""
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "credits_prompt_python.prompt"
create_file(prompt_file_path, "Credits test prompt")
output_file_path_str = str(temp_dir_setup["output_dir"] / "credits_output.py")
mock_construct_paths_fixture.return_value = (
{},
{"prompt_file": "Credits test prompt"},
{"output": output_file_path_str},
"python"
)
# Create 402 response with balance info
mock_response = MagicMock(spec=requests.Response)
mock_response.status_code = 402
mock_response.text = "Insufficient credits"
mock_response.json.return_value = {"error": "Insufficient credits", "currentBalance": 0.02, "estimatedCost": 0.05}
http_error = requests.exceptions.HTTPError(response=mock_response)
http_error.response = mock_response
mock_requests_post_fixture.side_effect = http_error
with pytest.raises(click.UsageError, match="Insufficient credits"):
code_generator_main(mock_ctx, str(prompt_file_path), output_file_path_str, None, False)
# Check that balance info was printed
printed_messages = [str(call_args[0][0]) for call_args in mock_rich_console_fixture.call_args_list if call_args[0]]
assert any("0.02" in msg and "0.05" in msg for msg in printed_messages), \
f"Expected balance/cost info in output. Got: {printed_messages}"
# Reset
mock_requests_post_fixture.side_effect = None
def test_full_gen_cloud_missing_env_vars_fallback_to_local(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture,
mock_local_generator_fixture, mock_rich_console_fixture, mock_get_jwt_token_fixture, monkeypatch
):
mock_ctx.obj['local'] = False
prompt_file_path = temp_dir_setup["prompts_dir"] / "env_var_prompt_python.prompt"
create_file(prompt_file_path, "Env var test prompt")
output_file_path_str = str(temp_dir_setup["output_dir"] / "env_var_output.py")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Env var test prompt"},
{"output": output_file_path_str},
"python"
)
# CloudConfig.get_jwt_token returns None when env vars are missing
# (it catches the AuthError internally)
mock_get_jwt_token_fixture.return_value = None
code_generator_main(mock_ctx, str(prompt_file_path), output_file_path_str, None, False)
# Local fallback should call generator with preprocess_prompt=False now
called_kwargs = mock_local_generator_fixture.call_args.kwargs
assert called_kwargs["prompt"] == "Env var test prompt"
assert called_kwargs["language"] == "python"
assert called_kwargs["strength"] == mock_ctx.obj['strength']
assert called_kwargs["temperature"] == mock_ctx.obj['temperature']
assert called_kwargs["time"] == mock_ctx.obj['time']
assert called_kwargs["verbose"] == mock_ctx.obj['verbose']
assert called_kwargs["preprocess_prompt"] is False
assert called_kwargs["output_schema"] is None
assert any("falling back to local" in str(call_args[0][0]).lower() for call_args in mock_rich_console_fixture.call_args_list if call_args[0])
# C. Incremental Generation
def test_incremental_gen_with_original_prompt_file(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_incremental_generator_fixture, mock_env_vars
):
prompt_file_path = temp_dir_setup["prompts_dir"] / "inc_prompt_python.prompt"
create_file(prompt_file_path, "New prompt content")
output_file_name = "inc_output.py"
output_file_path = temp_dir_setup["output_dir"] / output_file_name
create_file(output_file_path, "Existing code content")
original_prompt_file_path = temp_dir_setup["prompts_dir"] / "inc_original_python.prompt"
create_file(original_prompt_file_path, "Original prompt content")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{
"prompt_file": "New prompt content",
"original_prompt_file": "Original prompt content"
},
{"output": str(output_file_path)},
"python"
)
mock_incremental_generator_fixture.return_value = ("Updated code", True, 0.002, "inc_model")
code, incremental, cost, model = code_generator_main(
mock_ctx, str(prompt_file_path), str(output_file_path), str(original_prompt_file_path), False
)
assert code == "Updated code"
assert incremental
assert cost == 0.002
assert model == "inc_model"
call_kwargs = mock_incremental_generator_fixture.call_args.kwargs
assert call_kwargs["original_prompt"] == "Original prompt content"
assert call_kwargs["new_prompt"] == "New prompt content"
assert call_kwargs["existing_code"] == "Existing code content"
assert call_kwargs["language"] == "python"
assert call_kwargs["strength"] == 0.5
assert call_kwargs["temperature"] == 0.0
assert call_kwargs["time"] == 0.25
assert call_kwargs["force_incremental"] is False
assert call_kwargs["verbose"] is False
assert call_kwargs["preprocess_prompt"] is False
assert output_file_path.read_text() == "Updated code"
def test_incremental_gen_with_git_committed_prompt(
mock_ctx, temp_dir_setup, git_repo_setup, mock_construct_paths_fixture,
mock_incremental_generator_fixture, mock_subprocess_run_fixture, mock_env_vars
):
prompt_filename = "git_prompt_python.prompt"
prompt_file_path_in_git = git_repo_setup / prompt_filename
original_git_content = "Original git prompt from HEAD"
create_file(prompt_file_path_in_git, original_git_content)
def git_command_side_effect(*args, **kwargs):
cmd = args[0]
if "git" in cmd and "show" in cmd and f"HEAD:{prompt_filename}" in cmd[2]:
if pathlib.Path(kwargs.get("cwd", ".")).resolve() == git_repo_setup.resolve():
return subprocess.CompletedProcess(cmd, 0, stdout=original_git_content, stderr="")
if "git" in cmd and "rev-parse" in cmd and "--is-inside-work-tree" in cmd:
if (git_repo_setup / ".git").exists() and \
(pathlib.Path(kwargs.get("cwd")).resolve() == git_repo_setup.resolve() or \
str(git_repo_setup.resolve()) in str(pathlib.Path(kwargs.get("cwd")).resolve())):
return subprocess.CompletedProcess(cmd, 0, stdout="true", stderr="")
return subprocess.CompletedProcess(cmd, 0, stdout="false", stderr="")
if "git" in cmd and "rev-parse" in cmd and "--show-toplevel" in cmd:
if (git_repo_setup / ".git").exists():
return subprocess.CompletedProcess(cmd, 0, stdout=str(git_repo_setup.resolve()), stderr="")
return subprocess.CompletedProcess(cmd, 128, stdout="", stderr="Not a git repo")
if "git" in cmd and "status" in cmd and "--porcelain" in cmd and str(prompt_file_path_in_git.resolve()) in cmd:
return subprocess.CompletedProcess(cmd, 0, stdout=f" M {prompt_filename}", stderr="")
if "git" in cmd and "diff" in cmd and "--quiet" in cmd and "HEAD" in cmd and str(prompt_file_path_in_git.resolve()) in cmd:
return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="")
if "git" in cmd and "add" in cmd:
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
return subprocess.CompletedProcess(cmd, 0, stdout="default mock stdout", stderr="default mock stderr")
mock_subprocess_run_fixture.side_effect = git_command_side_effect
new_prompt_content_on_disk = "New git prompt content on disk"
create_file(prompt_file_path_in_git, new_prompt_content_on_disk)
output_file_name = "git_output.py"
output_file_path = temp_dir_setup["output_dir"] / output_file_name
create_file(output_file_path, "Existing code for git test")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": new_prompt_content_on_disk},
{"output": str(output_file_path)},
"python"
)
mock_incremental_generator_fixture.return_value = ("Git updated code", True, 0.003, "git_inc_model")
code, incremental, _, _ = code_generator_main(
mock_ctx, str(prompt_file_path_in_git), str(output_file_path), None, False
)
assert code == "Git updated code"
assert incremental
call_kwargs = mock_incremental_generator_fixture.call_args.kwargs
assert call_kwargs["language"] == "python"
assert call_kwargs["strength"] == 0.5
assert call_kwargs["temperature"] == 0.0
assert call_kwargs["time"] == 0.25
assert call_kwargs["force_incremental"] is False
assert call_kwargs["verbose"] is False
add_called_for_prompt = False
for call in mock_subprocess_run_fixture.call_args_list:
args_list = call[0][0]
if "git" in args_list and "add" in args_list and str(prompt_file_path_in_git.resolve()) in args_list:
add_called_for_prompt = True
break
assert add_called_for_prompt
mock_subprocess_run_fixture.side_effect = None
def test_incremental_gen_fallback_to_full_on_generator_suggestion(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture,
mock_pdd_preprocess_fixture,
mock_incremental_generator_fixture, mock_local_generator_fixture, mock_env_vars
):
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "inc_fallback_prompt.prompt"
create_file(prompt_file_path, "New prompt")
output_file_path = temp_dir_setup["output_dir"] / "inc_fallback_output.py"
create_file(output_file_path, "Existing code")
original_prompt_file_path = temp_dir_setup["prompts_dir"] / "inc_fallback_original.prompt"
create_file(original_prompt_file_path, "Original prompt")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "New prompt", "original_prompt_file": "Original prompt"},
{"output": str(output_file_path)},
"python"
)
mock_incremental_generator_fixture.return_value = (None, False, 0.001, "inc_model_suggests_full")
code_generator_main(
mock_ctx, str(prompt_file_path), str(output_file_path), str(original_prompt_file_path), False
)
call_kwargs = mock_incremental_generator_fixture.call_args.kwargs
assert call_kwargs["language"] == "python"
assert call_kwargs["strength"] == mock_ctx.obj['strength']
assert call_kwargs["temperature"] == mock_ctx.obj['temperature']
assert call_kwargs["time"] == mock_ctx.obj['time']
assert call_kwargs["force_incremental"] is False
assert call_kwargs["verbose"] == mock_ctx.obj['verbose']
def test_incremental_with_env_vars_substitution(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_incremental_generator_fixture, mock_env_vars
):
"""Ensure env_vars substitute in both original and new prompts before incremental call."""
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "inc_env_prompt.prompt"
output_file_path = temp_dir_setup["output_dir"] / "inc_env_output.py"
create_file(prompt_file_path, "New says $NAME")
create_file(output_file_path, "Existing code body")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "New says $NAME", "original_prompt_file": "Old says ${NAME}"},
{"output": str(output_file_path)},
"python",
)
code_generator_main(
mock_ctx,
str(prompt_file_path),
str(output_file_path),
None,
True,
env_vars={"NAME": "Alice", "llm": "true"},
)
call_kwargs = mock_incremental_generator_fixture.call_args.kwargs
assert call_kwargs["original_prompt"] == "Old says Alice"
assert call_kwargs["new_prompt"] == "New says Alice"
assert call_kwargs["preprocess_prompt"] is False
def test_unknown_variable_in_output_path_left_unchanged(
mock_ctx, temp_dir_setup, mock_construct_paths_fixture, mock_local_generator_fixture, mock_env_vars
):
mock_ctx.obj['local'] = True
prompt_file_path = temp_dir_setup["prompts_dir"] / "unk_out_prompt.prompt"
create_file(prompt_file_path, "Ignorable")
output_pattern = str(temp_dir_setup["output_dir"] / "out_${UNKNOWN}.txt")
mock_construct_paths_fixture.return_value = (
{}, # resolved_config
{"prompt_file": "Ignorable"},