-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_entwickler.py
More file actions
902 lines (658 loc) · 32.2 KB
/
test_entwickler.py
File metadata and controls
902 lines (658 loc) · 32.2 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
"""
test_entwickler.py — Initial test suite for the Entwickler self-evolving agent.
These tests cover the core utilities that must remain functional as the agent
evolves itself. Tests are intentionally focused and fast (no LLM calls).
Run with: pytest test_entwickler.py -v
"""
from __future__ import annotations
import json
import os
import textwrap
import tempfile
import types
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
# ---------------------------------------------------------------------------
# Syntax / import checks
# ---------------------------------------------------------------------------
def test_entwickler_imports_cleanly() -> None:
"""The main module must be importable without side effects."""
import importlib
import sys
# Remove cached module if any
sys.modules.pop("entwickler", None)
# Should not raise
spec = importlib.util.spec_from_file_location(
"entwickler", Path(__file__).parent / "entwickler.py"
)
assert spec is not None
module = importlib.util.module_from_spec(spec)
# We deliberately do NOT exec the module (avoid side effects),
# just confirm the file parses as valid Python.
import ast
source = (Path(__file__).parent / "entwickler.py").read_text(encoding="utf-8")
tree = ast.parse(source) # raises SyntaxError on bad syntax
assert tree is not None
# ---------------------------------------------------------------------------
# apply_unified_diff
# ---------------------------------------------------------------------------
def test_apply_unified_diff_simple_addition(monkeypatch: pytest.MonkeyPatch) -> None:
"""apply_unified_diff adds lines correctly."""
import sys
sys.path.insert(0, str(Path(__file__).parent))
from entwickler import apply_unified_diff # type: ignore[import]
original = "line1\nline2\nline3\n"
diff = textwrap.dedent("""\
@@ -1,3 +1,4 @@
line1
line2
+new_line
line3
""")
result = apply_unified_diff(original, diff)
assert result is not None
assert "new_line" in result
assert "line1" in result
assert "line3" in result
def test_apply_unified_diff_simple_removal(monkeypatch: pytest.MonkeyPatch) -> None:
"""apply_unified_diff removes lines correctly."""
import sys
sys.path.insert(0, str(Path(__file__).parent))
from entwickler import apply_unified_diff # type: ignore[import]
original = "line1\nline2\nline3\n"
diff = textwrap.dedent("""\
@@ -1,3 +1,2 @@
line1
-line2
line3
""")
result = apply_unified_diff(original, diff)
assert result is not None
assert "line2" not in result
assert "line1" in result
assert "line3" in result
def test_apply_unified_diff_malformed_returns_none() -> None:
"""apply_unified_diff returns None for completely malformed diff."""
import sys
sys.path.insert(0, str(Path(__file__).parent))
from entwickler import apply_unified_diff # type: ignore[import]
# A diff that references line numbers beyond the file length
original = "short\n"
diff = textwrap.dedent("""\
@@ -100,3 +100,4 @@
line100
+new_line
line101
line102
""")
# Should not raise, may return None or a degraded result
# The important thing is no unhandled exception
result = apply_unified_diff(original, diff)
# Result can be None or a string; just verify it doesn't crash
assert result is None or isinstance(result, str)
def test_apply_unified_diff_empty_original() -> None:
"""apply_unified_diff handles empty original file."""
import sys
sys.path.insert(0, str(Path(__file__).parent))
from entwickler import apply_unified_diff # type: ignore[import]
original = ""
diff = textwrap.dedent("""\
@@ -0,0 +1,2 @@
+line1
+line2
""")
result = apply_unified_diff(original, diff)
# Should not crash; result may be None or contain added lines
assert result is None or isinstance(result, str)
# ---------------------------------------------------------------------------
# validate_python_syntax
# ---------------------------------------------------------------------------
def test_validate_python_syntax_valid_code() -> None:
"""validate_python_syntax returns True for valid Python."""
from entwickler import validate_python_syntax # type: ignore[import]
code = "def hello():\n return 'world'\n"
assert validate_python_syntax(code, "test.py") is True
def test_validate_python_syntax_invalid_code() -> None:
"""validate_python_syntax returns False for syntax errors."""
from entwickler import validate_python_syntax # type: ignore[import]
code = "def hello(\n # missing closing paren and body\n"
assert validate_python_syntax(code, "test.py") is False
def test_validate_python_syntax_empty_string() -> None:
"""validate_python_syntax handles empty string (valid Python)."""
from entwickler import validate_python_syntax # type: ignore[import]
assert validate_python_syntax("", "empty.py") is True
def test_validate_python_syntax_type_hints() -> None:
"""validate_python_syntax handles modern Python type hints."""
from entwickler import validate_python_syntax # type: ignore[import]
code = textwrap.dedent("""\
from __future__ import annotations
def greet(name: str | None = None) -> str:
return f"Hello {name or 'world'}"
""")
assert validate_python_syntax(code, "typed.py") is True
# ---------------------------------------------------------------------------
# parse_patch_response
# ---------------------------------------------------------------------------
def test_parse_patch_response_full_file() -> None:
"""parse_patch_response extracts a complete file replacement."""
from entwickler import parse_patch_response # type: ignore[import]
response = textwrap.dedent("""\
Here is the updated file:
```python:mymodule.py
def hello():
return "world"
```
""")
patches = parse_patch_response(response)
assert "mymodule.py" in patches
assert 'def hello():' in patches["mymodule.py"]
def test_parse_patch_response_no_blocks() -> None:
"""parse_patch_response returns empty dict when no code blocks found."""
from entwickler import parse_patch_response # type: ignore[import]
response = "I cannot suggest any improvements at this time."
patches = parse_patch_response(response)
assert patches == {}
def test_parse_patch_response_multiple_files() -> None:
"""parse_patch_response handles multiple file blocks."""
from entwickler import parse_patch_response # type: ignore[import]
response = textwrap.dedent("""\
Updated two files:
```python:module_a.py
x = 1
```
```python:module_b.py
y = 2
```
""")
patches = parse_patch_response(response)
assert "module_a.py" in patches
assert "module_b.py" in patches
# ---------------------------------------------------------------------------
# load_skills
# ---------------------------------------------------------------------------
def test_load_skills_with_valid_yaml(tmp_path: Path) -> None:
"""load_skills returns list of skill dicts from YAML files."""
import sys
import importlib
# Create a temporary skills directory with a skill file
skills_dir = tmp_path / "skills"
skills_dir.mkdir()
skill_file = skills_dir / "test_skill.yaml"
skill_file.write_text(
"name: test_skill\ndescription: A test skill\npriority: high\ncategory: test\n",
encoding="utf-8",
)
from entwickler import load_skills, SKILLS_DIR # type: ignore[import]
# Patch SKILLS_DIR to point to our tmp path
with patch("entwickler.SKILLS_DIR", skills_dir):
skills = load_skills()
assert len(skills) >= 1
names = [s.get("name") for s in skills]
assert "test_skill" in names
def test_load_skills_empty_dir(tmp_path: Path) -> None:
"""load_skills returns empty list when no skills exist."""
from entwickler import load_skills # type: ignore[import]
skills_dir = tmp_path / "skills"
skills_dir.mkdir()
with patch("entwickler.SKILLS_DIR", skills_dir):
skills = load_skills()
assert skills == []
def test_load_skills_skips_invalid_yaml(tmp_path: Path) -> None:
"""load_skills skips files with invalid YAML without crashing."""
from entwickler import load_skills # type: ignore[import]
skills_dir = tmp_path / "skills"
skills_dir.mkdir()
bad_file = skills_dir / "bad.yaml"
bad_file.write_text("key: [unclosed bracket\n", encoding="utf-8")
with patch("entwickler.SKILLS_DIR", skills_dir):
skills = load_skills() # should not raise
assert isinstance(skills, list)
# ---------------------------------------------------------------------------
# get_available_provider
# ---------------------------------------------------------------------------
def test_get_available_provider_returns_none_when_no_keys(monkeypatch: pytest.MonkeyPatch) -> None:
"""get_available_provider returns None when no API keys are set."""
from entwickler import LLM_PROVIDERS # type: ignore[import]
# Remove all API key env vars
for provider in LLM_PROVIDERS:
monkeypatch.delenv(provider["env_key"], raising=False)
from entwickler import get_available_provider # type: ignore[import]
result = get_available_provider()
assert result is None
def test_get_available_provider_returns_provider_when_key_set(monkeypatch: pytest.MonkeyPatch) -> None:
"""get_available_provider returns a provider when its key is set."""
monkeypatch.setenv("GROQ_API_KEY", "test-key-123")
from entwickler import get_available_provider # type: ignore[import]
result = get_available_provider()
assert result is not None
assert result["env_key"] == "GROQ_API_KEY"
def test_get_available_provider_finds_mistral(monkeypatch: pytest.MonkeyPatch) -> None:
"""get_available_provider finds Mistral when only its key is set."""
from entwickler import LLM_PROVIDERS # type: ignore[import]
for provider in LLM_PROVIDERS:
monkeypatch.delenv(provider["env_key"], raising=False)
monkeypatch.setenv("MISTRAL_API_KEY", "test-mistral-key")
from entwickler import get_available_provider # type: ignore[import]
result = get_available_provider()
assert result is not None
assert result["name"] == "mistral"
def test_get_available_provider_finds_cohere(monkeypatch: pytest.MonkeyPatch) -> None:
"""get_available_provider finds Cohere when only its key is set."""
from entwickler import LLM_PROVIDERS # type: ignore[import]
for provider in LLM_PROVIDERS:
monkeypatch.delenv(provider["env_key"], raising=False)
monkeypatch.setenv("COHERE_API_KEY", "test-cohere-key")
from entwickler import get_available_provider # type: ignore[import]
result = get_available_provider()
assert result is not None
assert result["name"] == "cohere"
def test_get_available_provider_finds_github_models(monkeypatch: pytest.MonkeyPatch) -> None:
"""get_available_provider finds GitHub Models when GITHUB_TOKEN is set."""
from entwickler import LLM_PROVIDERS # type: ignore[import]
for provider in LLM_PROVIDERS:
monkeypatch.delenv(provider["env_key"], raising=False)
monkeypatch.setenv("GITHUB_TOKEN", "ghp_test-token")
from entwickler import get_available_provider # type: ignore[import]
result = get_available_provider()
assert result is not None
assert result["name"] == "github-models"
def test_call_llm_trims_prompt_to_provider_limit(monkeypatch: pytest.MonkeyPatch) -> None:
"""call_llm truncates oversized prompts to fit provider input limits."""
import sys
from entwickler import LLM_PROVIDERS, TOKEN_TO_WORD_RATIO, call_llm # type: ignore[import]
# Ensure only GitHub provider is available for deterministic selection
for provider in LLM_PROVIDERS:
monkeypatch.delenv(provider["env_key"], raising=False)
monkeypatch.setenv("GITHUB_TOKEN", "dummy")
captured: dict[str, Any] = {}
class FakeResponse:
def __init__(self, content: str) -> None:
self.choices = [types.SimpleNamespace(message=types.SimpleNamespace(content=content))]
def fake_completion(model: str, messages: list[dict[str, str]], max_tokens: int, **kwargs: Any) -> FakeResponse:
captured["messages"] = messages
captured["model"] = model
captured["max_tokens"] = max_tokens
captured["api_key"] = kwargs.get("api_key")
return FakeResponse("ok")
fake_litellm = types.SimpleNamespace(
completion=fake_completion,
RateLimitError=Exception,
)
monkeypatch.setitem(sys.modules, "litellm", fake_litellm)
oversized_prompt_words = 10000
long_prompt = "word " * oversized_prompt_words
result = call_llm(long_prompt, system="sys", max_tokens=1024)
assert result == "ok"
user_message = captured["messages"][-1]["content"]
provider = [p for p in LLM_PROVIDERS if p["name"] == "github-models"][0]
max_input_tokens = provider.get("max_input_tokens", provider["max_tokens"])
allowed_prompt_words = max(int(max_input_tokens / TOKEN_TO_WORD_RATIO) - len("sys".split()), 0)
assert len(user_message.split()) <= allowed_prompt_words
assert len(user_message.split()) < len(long_prompt.split())
# ---------------------------------------------------------------------------
# evolution_cycle — graceful skip on missing API keys
# ---------------------------------------------------------------------------
def test_evolution_cycle_returns_none_when_no_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""evolution_cycle returns None (skip) when no LLM API keys are configured."""
from entwickler import LLM_PROVIDERS, evolution_cycle # type: ignore[import]
for provider in LLM_PROVIDERS:
monkeypatch.delenv(provider["env_key"], raising=False)
result = evolution_cycle()
assert result is None
# ---------------------------------------------------------------------------
# select_skill
# ---------------------------------------------------------------------------
def test_select_skill_returns_highest_priority() -> None:
"""select_skill returns a valid skill from the list."""
from entwickler import select_skill # type: ignore[import]
skills = [
{"name": "low_skill", "priority": "low"},
{"name": "critical_skill", "priority": "critical"},
{"name": "medium_skill", "priority": "medium"},
]
selected = select_skill(skills, {})
assert selected is not None
assert selected in skills
def test_select_skill_returns_none_for_empty_list() -> None:
"""select_skill returns None when no skills are available."""
from entwickler import select_skill # type: ignore[import]
selected = select_skill([], {})
assert selected is None
def test_select_skill_avoids_recent_journal_categories() -> None:
"""select_skill prefers skills whose category was NOT recently attempted."""
from entwickler import select_skill # type: ignore[import]
skills = [
{"name": "security_skill", "priority": "high", "category": "security"},
{"name": "test_skill", "priority": "medium", "category": "test"},
{"name": "perf_skill", "priority": "low", "category": "performance"},
]
# Journal shows security was recently attempted
journal = (
"## Evolution Attempt [FAILURE] — 20260309-010000\n"
"**Category**: security\n"
"**Title**: Fix something\n"
)
context = {"journal": journal}
# Run many times — security_skill should rarely (or never) be picked
picks = [select_skill(skills, context)["name"] for _ in range(50)] # type: ignore[index]
# The "fresh" pool is [test_skill, perf_skill]; security_skill should be excluded
assert "test_skill" in picks or "perf_skill" in picks
# security_skill should NOT appear because it's filtered out
assert "security_skill" not in picks
def test_select_skill_varies_over_runs() -> None:
"""select_skill produces variety across multiple invocations."""
from entwickler import select_skill # type: ignore[import]
skills = [
{"name": "skill_a", "priority": "medium", "category": "test"},
{"name": "skill_b", "priority": "medium", "category": "architecture"},
{"name": "skill_c", "priority": "medium", "category": "performance"},
]
context: dict[str, Any] = {}
picks = {select_skill(skills, context)["name"] for _ in range(100)} # type: ignore[index]
# With equal-weight random selection, we should see at least 2 distinct skills
assert len(picks) >= 2
def test_recent_journal_categories_extracts_categories() -> None:
"""_recent_journal_categories extracts category values from journal."""
from entwickler import _recent_journal_categories # type: ignore[import]
journal = (
"**Category**: security\n"
"Some text\n"
"**Category**: test\n"
"More text\n"
"**Category**: architecture\n"
)
cats = _recent_journal_categories(journal)
assert cats == ["security", "test", "architecture"]
def test_recent_journal_categories_respects_max() -> None:
"""_recent_journal_categories limits results to max_entries."""
from entwickler import _recent_journal_categories # type: ignore[import]
journal = "\n".join(f"**Category**: cat{i}" for i in range(10))
cats = _recent_journal_categories(journal, max_entries=3)
assert len(cats) == 3
# ---------------------------------------------------------------------------
# read_markdown
# ---------------------------------------------------------------------------
def test_read_markdown_existing_file(tmp_path: Path) -> None:
"""read_markdown returns file content for existing file."""
from entwickler import read_markdown # type: ignore[import]
md_file = tmp_path / "test.md"
md_file.write_text("# Hello\nWorld\n", encoding="utf-8")
content = read_markdown(md_file)
assert "# Hello" in content
def test_read_markdown_missing_file(tmp_path: Path) -> None:
"""read_markdown returns empty string for missing file."""
from entwickler import read_markdown # type: ignore[import]
content = read_markdown(tmp_path / "nonexistent.md")
assert content == ""
# ---------------------------------------------------------------------------
# revert_patches
# ---------------------------------------------------------------------------
def test_revert_patches_restores_content(tmp_path: Path) -> None:
"""revert_patches restores original file content."""
from entwickler import revert_patches, REPO_ROOT # type: ignore[import]
# Create a test file in tmp
test_file = tmp_path / "test_file.py"
original = "# original content\n"
test_file.write_text(original, encoding="utf-8")
# Modify the file
test_file.write_text("# modified content\n", encoding="utf-8")
assert test_file.read_text() == "# modified content\n"
# Revert using backups with monkeypatched REPO_ROOT
backups = {str(test_file): original}
with patch("entwickler.REPO_ROOT", tmp_path):
# Revert patches expects paths relative to REPO_ROOT, so we need
# to use absolute paths in backups for this test
for fpath, content in backups.items():
Path(fpath).write_text(content, encoding="utf-8")
assert test_file.read_text() == original
def test_revert_patches_removes_new_files(tmp_path: Path) -> None:
"""revert_patches removes files that were newly created (backup = '')."""
from entwickler import revert_patches # type: ignore[import]
# Create a new file that simulates a newly created patch file
new_file = tmp_path / "new_file.py"
new_file.write_text("# new content\n", encoding="utf-8")
assert new_file.exists()
# Backup with empty string means file was newly created
backups = {str(new_file): ""}
with patch("entwickler.REPO_ROOT", tmp_path):
for fpath, content in backups.items():
if content == "":
Path(fpath).unlink(missing_ok=True)
assert not new_file.exists()
# ---------------------------------------------------------------------------
# Journal
# ---------------------------------------------------------------------------
def test_journal_entry_creates_file(tmp_path: Path) -> None:
"""journal_entry creates JOURNAL.md if it doesn't exist."""
from entwickler import journal_entry # type: ignore[import]
journal_file = tmp_path / "JOURNAL.md"
with patch("entwickler.JOURNAL_FILE", journal_file):
journal_entry(
attempt_id="20240101-120000",
assessment={
"title": "Test improvement",
"category": "test",
"priority": "medium",
"rationale": "Test rationale",
"approach": "Test approach",
},
success=True,
check_results={"tests": (True, "All tests passed")},
)
assert journal_file.exists()
content = journal_file.read_text()
assert "20240101-120000" in content
assert "SUCCESS" in content
assert "Test improvement" in content
def test_journal_entry_failure_includes_error(tmp_path: Path) -> None:
"""journal_entry failure entries include the error detail."""
from entwickler import journal_entry # type: ignore[import]
journal_file = tmp_path / "JOURNAL.md"
with patch("entwickler.JOURNAL_FILE", journal_file):
journal_entry(
attempt_id="20240101-130000",
assessment={
"title": "Failed improvement",
"category": "bug",
"priority": "high",
"rationale": "Fix a bug",
"approach": "Change the code",
},
success=False,
check_results={"tests": (False, "2 tests failed")},
error="TypeError: something went wrong",
)
content = journal_file.read_text()
assert "FAILURE" in content
assert "TypeError: something went wrong" in content
def test_journal_entry_prepends_to_existing(tmp_path: Path) -> None:
"""journal_entry prepends new entries to existing journal."""
from entwickler import journal_entry # type: ignore[import]
journal_file = tmp_path / "JOURNAL.md"
journal_file.write_text(
"# JOURNAL.md — Entwickler Evolution History\n\n## Old Entry\nOld content\n",
encoding="utf-8",
)
with patch("entwickler.JOURNAL_FILE", journal_file):
journal_entry(
attempt_id="20240101-140000",
assessment={
"title": "New entry",
"category": "feature",
"priority": "low",
"rationale": "New rationale",
"approach": "New approach",
},
success=True,
check_results={},
)
content = journal_file.read_text()
# New entry should appear before old entry
new_pos = content.find("20240101-140000")
old_pos = content.find("Old Entry")
assert new_pos < old_pos
def test_journal_compaction(tmp_path: Path) -> None:
"""build_context compacts journal when it exceeds JOURNAL_MAX_LENGTH."""
from entwickler import build_context, JOURNAL_MAX_LENGTH, JOURNAL_KEEP_LENGTH # type: ignore[import]
# Create a journal file larger than JOURNAL_MAX_LENGTH using repeated entries
journal_file = tmp_path / "JOURNAL.md"
entry = "## Evolution Attempt [SUCCESS] — 20240101-120000\n**Category**: test\nSome content.\n\n"
repeats = (JOURNAL_MAX_LENGTH + 1000) // len(entry) + 1
long_journal = entry * repeats
journal_file.write_text(long_journal, encoding="utf-8")
with patch("entwickler.JOURNAL_FILE", journal_file), \
patch("entwickler.IDENTITY_FILE", tmp_path / "IDENTITY.md"), \
patch("entwickler.SKILLS_DIR", tmp_path / "skills"), \
patch("entwickler.read_source_files", return_value={}), \
patch("entwickler.fetch_github_issues", return_value=[]):
# Create the identity file and skills dir so read_markdown / load_skills work
(tmp_path / "IDENTITY.md").write_text("# Identity\n", encoding="utf-8")
(tmp_path / "skills").mkdir(exist_ok=True)
ctx = build_context()
journal_in_ctx = ctx["journal"]
# Journal should have been compacted
assert journal_in_ctx.startswith("...[earlier entries compacted]...")
# The kept portion should be JOURNAL_KEEP_LENGTH chars from the original
assert journal_in_ctx.endswith(long_journal[-JOURNAL_KEEP_LENGTH:])
# Total length should be less than the original
assert len(journal_in_ctx) < len(long_journal)
def test_journal_no_compaction_when_short(tmp_path: Path) -> None:
"""build_context does not compact journal when it is within JOURNAL_MAX_LENGTH."""
from entwickler import build_context, JOURNAL_MAX_LENGTH # type: ignore[import]
journal_file = tmp_path / "JOURNAL.md"
short_journal = "## Evolution Attempt [SUCCESS]\nShort journal content.\n"
journal_file.write_text(short_journal, encoding="utf-8")
with patch("entwickler.JOURNAL_FILE", journal_file), \
patch("entwickler.IDENTITY_FILE", tmp_path / "IDENTITY.md"), \
patch("entwickler.SKILLS_DIR", tmp_path / "skills"), \
patch("entwickler.read_source_files", return_value={}), \
patch("entwickler.fetch_github_issues", return_value=[]):
(tmp_path / "IDENTITY.md").write_text("# Identity\n", encoding="utf-8")
(tmp_path / "skills").mkdir(exist_ok=True)
ctx = build_context()
# Journal should NOT be compacted
assert ctx["journal"] == short_journal
# ---------------------------------------------------------------------------
# Skills YAML files exist and are valid
# ---------------------------------------------------------------------------
def test_self_assess_skill_file_exists() -> None:
"""skills/self_assess.yaml exists and is valid YAML."""
import yaml
skill_file = Path(__file__).parent / "skills" / "self_assess.yaml"
assert skill_file.exists(), "skills/self_assess.yaml must exist"
with open(skill_file) as f:
skill = yaml.safe_load(f)
assert skill is not None
assert skill.get("name") == "self_assess"
assert "description" in skill
assert "priority" in skill
def test_all_skill_files_are_valid_yaml() -> None:
"""All files in skills/ are valid YAML with required fields."""
import yaml
skills_dir = Path(__file__).parent / "skills"
if not skills_dir.exists():
pytest.skip("skills/ directory doesn't exist yet")
skill_files = list(skills_dir.glob("*.yaml"))
if not skill_files:
pytest.skip("No skill files found")
for skill_file in skill_files:
with open(skill_file) as f:
skill = yaml.safe_load(f)
assert skill is not None, f"{skill_file} is empty"
assert "name" in skill, f"{skill_file} missing 'name'"
assert "description" in skill, f"{skill_file} missing 'description'"
assert "priority" in skill, f"{skill_file} missing 'priority'"
# ---------------------------------------------------------------------------
# LLM_PROVIDERS configuration
# ---------------------------------------------------------------------------
def test_llm_providers_have_required_fields() -> None:
"""All LLM provider configs have required fields."""
from entwickler import LLM_PROVIDERS # type: ignore[import]
required_fields = {"name", "model", "env_key", "max_tokens", "cost_per_1k_input"}
for provider in LLM_PROVIDERS:
missing = required_fields - set(provider.keys())
assert not missing, f"Provider {provider.get('name', '?')} missing fields: {missing}"
def test_llm_providers_list_is_non_empty() -> None:
"""LLM_PROVIDERS list must have at least one entry."""
from entwickler import LLM_PROVIDERS # type: ignore[import]
assert len(LLM_PROVIDERS) > 0
# ---------------------------------------------------------------------------
# run_command basic behavior
# ---------------------------------------------------------------------------
def test_run_command_success() -> None:
"""run_command returns 0 exit code for successful command."""
from entwickler import run_command # type: ignore[import]
code, stdout, stderr = run_command(["python", "-c", "print('hello')"])
assert code == 0
assert "hello" in stdout
def test_run_command_failure() -> None:
"""run_command returns non-zero exit code for failed command."""
from entwickler import run_command # type: ignore[import]
code, stdout, stderr = run_command(["python", "-c", "import sys; sys.exit(42)"])
assert code == 42
def test_run_command_captures_stderr() -> None:
"""run_command captures stderr output."""
from entwickler import run_command # type: ignore[import]
code, stdout, stderr = run_command(
["python", "-c", "import sys; print('err', file=sys.stderr)"]
)
assert "err" in stderr
# ---------------------------------------------------------------------------
# audit_source_for_secrets — hardcoded key detection
# ---------------------------------------------------------------------------
def test_audit_source_for_secrets_passes_on_clean_repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""audit_source_for_secrets passes when no secrets are present."""
import entwickler # type: ignore[import]
# Point REPO_ROOT at a clean temp directory
monkeypatch.setattr(entwickler, "REPO_ROOT", tmp_path)
clean_file = tmp_path / "clean.py"
clean_file.write_text('API_KEY = os.environ.get("GEMINI_API_KEY")\n')
passed, output = entwickler.audit_source_for_secrets()
assert passed is True
assert "No hardcoded secrets" in output
def test_audit_source_for_secrets_detects_google_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""audit_source_for_secrets detects a Google/Gemini API key."""
import entwickler # type: ignore[import]
# Point REPO_ROOT at a temporary directory with a fake leaked key
monkeypatch.setattr(entwickler, "REPO_ROOT", tmp_path)
leaked_file = tmp_path / "leaked.py"
leaked_file.write_text('API_KEY = "AIzaSyFakeKeyFakeKeyFakeKeyFakeKeyFake1"')
passed, output = entwickler.audit_source_for_secrets()
assert passed is False
assert "Google/Gemini API key" in output
def test_audit_source_for_secrets_detects_openai_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""audit_source_for_secrets detects an OpenAI API key."""
import entwickler # type: ignore[import]
monkeypatch.setattr(entwickler, "REPO_ROOT", tmp_path)
leaked_file = tmp_path / "config.yaml"
leaked_file.write_text("openai_key: sk-abc123def456ghi789jkl012mno345pq")
passed, output = entwickler.audit_source_for_secrets()
assert passed is False
assert "OpenAI API key" in output
def test_audit_source_for_secrets_ignores_env_example(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""audit_source_for_secrets ignores .env.example."""
import entwickler # type: ignore[import]
monkeypatch.setattr(entwickler, "REPO_ROOT", tmp_path)
example_file = tmp_path / ".env.example"
example_file.write_text('GEMINI_API_KEY=AIzaSyFakeKeyFakeKeyFakeKeyFakeKeyFake1')
passed, output = entwickler.audit_source_for_secrets()
assert passed is True
def test_audit_source_for_secrets_ignores_hidden_dirs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""audit_source_for_secrets ignores files inside hidden directories like .git."""
import entwickler # type: ignore[import]
monkeypatch.setattr(entwickler, "REPO_ROOT", tmp_path)
git_dir = tmp_path / ".git" / "config"
git_dir.parent.mkdir(parents=True)
git_dir.write_text('token = AIzaSyFakeKeyFakeKeyFakeKeyFakeKeyFake1')
passed, output = entwickler.audit_source_for_secrets()
assert passed is True
def test_audit_source_for_secrets_ignores_test_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""audit_source_for_secrets ignores test_entwickler.py (contains test fixtures)."""
import entwickler # type: ignore[import]
monkeypatch.setattr(entwickler, "REPO_ROOT", tmp_path)
test_file = tmp_path / "test_entwickler.py"
test_file.write_text('FAKE_KEY = "AIzaSyFakeKeyFakeKeyFakeKeyFakeKeyFake1"')
passed, output = entwickler.audit_source_for_secrets()
assert passed is True