forked from hyphen-2025/cyber-pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_files_utils.py
More file actions
487 lines (397 loc) · 18.8 KB
/
test_files_utils.py
File metadata and controls
487 lines (397 loc) · 18.8 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
"""
Test files utility functions.
Tests load_text, find_adapter_directory and related file operations.
"""
import unittest
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
sys.path.insert(0, str(Path(__file__).parent.parent / "skills" / "cypilot" / "scripts"))
from cypilot.utils.files import load_text, find_cypilot_directory as find_adapter_directory
from cypilot.utils.files import (
cfg_get_str,
cypilot_root_from_project_config,
iter_registry_entries,
load_cypilot_config as load_adapter_config,
load_artifacts_registry,
load_project_config,
)
class TestLoadText(unittest.TestCase):
"""Test load_text function."""
def test_load_text_existing_file(self):
"""Test loading text from existing file."""
with TemporaryDirectory() as tmpdir:
test_file = Path(tmpdir) / "test.md"
test_file.write_text("Test content\nLine 2")
content, error = load_text(test_file)
self.assertIsNone(error)
self.assertEqual(content, "Test content\nLine 2")
def test_load_text_nonexistent_file(self):
"""Test loading text from nonexistent file returns error."""
with TemporaryDirectory() as tmpdir:
test_file = Path(tmpdir) / "nonexistent.md"
content, error = load_text(test_file)
# Function returns empty string on error, not None
self.assertEqual(content, "")
self.assertIsNotNone(error)
self.assertIn("not found", error.lower())
def test_load_text_empty_file(self):
"""Test loading text from empty file."""
with TemporaryDirectory() as tmpdir:
test_file = Path(tmpdir) / "empty.md"
test_file.write_text("")
content, error = load_text(test_file)
self.assertIsNone(error)
self.assertEqual(content, "")
def test_load_text_not_a_file(self):
"""Cover Not a file branch."""
with TemporaryDirectory() as tmpdir:
d = Path(tmpdir) / "dir"
d.mkdir()
content, error = load_text(d)
self.assertEqual(content, "")
self.assertIsNotNone(error)
self.assertIn("Not a file", str(error))
def test_load_text_read_exception(self):
"""Cover generic exception while reading file."""
with TemporaryDirectory() as tmpdir:
p = Path(tmpdir) / "x.md"
p.write_text("x", encoding="utf-8")
orig = Path.read_text
def boom(self, *args, **kwargs):
raise OSError("boom")
try:
Path.read_text = boom # type: ignore
content, error = load_text(p)
self.assertEqual(content, "")
self.assertIsNotNone(error)
self.assertIn("Failed to read", str(error))
finally:
Path.read_text = orig # type: ignore
class TestFindAdapterDirectory(unittest.TestCase):
"""Test find_adapter_directory function."""
def test_find_adapter_with_agents_md(self):
"""Test finding adapter directory with AGENTS.md."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
# Create .git to mark as project root
(root / ".git").mkdir()
adapter_dir = root / ".cypilot-adapter"
adapter_dir.mkdir()
# Create AGENTS.md with adapter markers
(adapter_dir / "AGENTS.md").write_text("# Cypilot Adapter: Test\n\nThis is an Cypilot adapter for testing.")
# Create specs directory (required for validation)
specs_dir = adapter_dir / "specs"
specs_dir.mkdir()
(specs_dir / "test.md").write_text("# Spec")
result = find_adapter_directory(root)
self.assertIsNotNone(result)
self.assertEqual(result.resolve(), adapter_dir.resolve())
def test_find_adapter_config_path_valid_wins(self):
"""When AGENTS.md TOML block specifies valid adapter path, it should be returned."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
(root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "cfg-adapter"\n```\n',
encoding="utf-8",
)
adapter_dir = root / "cfg-adapter"
adapter_dir.mkdir()
(adapter_dir / "config").mkdir()
(adapter_dir / "config" / "AGENTS.md").write_text("# Cypilot Adapter: X\n", encoding="utf-8")
result = find_adapter_directory(root)
self.assertIsNotNone(result)
self.assertEqual(result.resolve(), adapter_dir.resolve())
def test_find_adapter_config_path_invalid_no_fallback(self):
"""When AGENTS.md TOML block points to missing dir, find_adapter_directory must return None."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
(root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "missing"\n```\n',
encoding="utf-8",
)
# A valid adapter exists elsewhere, but must NOT be used.
adapter_dir = root / ".cypilot-adapter"
adapter_dir.mkdir()
(adapter_dir / "config").mkdir()
(adapter_dir / "config" / "AGENTS.md").write_text("# Cypilot Adapter: X\n", encoding="utf-8")
result = find_adapter_directory(root)
self.assertIsNone(result)
def test_find_adapter_recursive_permission_error_returns_none(self):
"""Cover recursive search PermissionError path."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
# Monkeypatch Path.iterdir to raise PermissionError.
orig_iterdir = Path.iterdir
def boom(self):
raise PermissionError("no")
try:
Path.iterdir = boom # type: ignore
result = find_adapter_directory(root)
self.assertIsNone(result)
finally:
Path.iterdir = orig_iterdir # type: ignore
def test_find_adapter_extends_matches_cypilot_root(self):
"""Cover is_adapter_directory Extends path validation with provided cypilot_root."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
cypilot_root = root / "Cypilot"
cypilot_root.mkdir()
(cypilot_root / "AGENTS.md").write_text("# Core\n", encoding="utf-8")
(cypilot_root / "requirements").mkdir()
(cypilot_root / "workflows").mkdir()
adapter_dir = root / ".cypilot-adapter"
adapter_dir.mkdir()
(adapter_dir / "AGENTS.md").write_text("# Cypilot Adapter: P\n\n**Extends**: `../Cypilot/AGENTS.md`\n", encoding="utf-8")
found = find_adapter_directory(root, cypilot_root=cypilot_root)
self.assertIsNotNone(found)
self.assertEqual(found.resolve(), adapter_dir.resolve())
class TestConfigHelpers(unittest.TestCase):
def test_cfg_get_str_variants(self):
cfg = {"a": " x ", "b": ""}
self.assertEqual(cfg_get_str(cfg, "b", "a"), "x")
self.assertIsNone(cfg_get_str(cfg, "missing"))
self.assertIsNone(cfg_get_str("not-dict", "a"))
def test_load_project_config_no_agents_md_returns_none(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
# No AGENTS.md at all
self.assertIsNone(load_project_config(root))
def test_load_project_config_invalid_toml_returns_none(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "adapter"\n```\n',
encoding="utf-8",
)
adapter = root / "adapter" / "config"
adapter.mkdir(parents=True)
(adapter / "core.toml").write_text("{not valid toml", encoding="utf-8")
self.assertIsNone(load_project_config(root))
def test_cypilot_root_from_project_config_success(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
cypilot_core = root / "Cypilot"
cypilot_core.mkdir()
(cypilot_core / "AGENTS.md").write_text("# Core\n", encoding="utf-8")
(cypilot_core / "requirements").mkdir()
(cypilot_core / "workflows").mkdir()
# New layout: AGENTS.md TOML block + config/core.toml with [paths] core
(root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "adapter"\n```\n',
encoding="utf-8",
)
adapter = root / "adapter" / "config"
adapter.mkdir(parents=True)
(adapter / "core.toml").write_text(
'[paths]\ncore = "../Cypilot"\n',
encoding="utf-8",
)
# Run from a subdir to exercise find_project_root via cwd.
sub = root / "src"
sub.mkdir()
cwd = Path.cwd()
try:
import os
os.chdir(str(sub))
found = cypilot_root_from_project_config()
self.assertIsNotNone(found)
self.assertEqual(found.resolve(), cypilot_core.resolve())
finally:
import os
os.chdir(str(cwd))
def test_cypilot_root_from_project_config_missing_key_returns_none(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
# AGENTS.md + core.toml exist but no [paths] core key
(root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "adapter"\n```\n',
encoding="utf-8",
)
adapter = root / "adapter" / "config"
adapter.mkdir(parents=True)
(adapter / "core.toml").write_text('version = "1.0"\n', encoding="utf-8")
sub = root / "src"
sub.mkdir()
cwd = Path.cwd()
try:
import os
os.chdir(str(sub))
self.assertIsNone(cypilot_root_from_project_config())
finally:
import os
os.chdir(str(cwd))
def test_cypilot_root_from_project_config_invalid_core_dir_returns_none(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
(root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "adapter"\n```\n',
encoding="utf-8",
)
adapter = root / "adapter" / "config"
adapter.mkdir(parents=True)
(adapter / "core.toml").write_text('[paths]\ncore = "MissingCypilot"\n', encoding="utf-8")
cwd = Path.cwd()
try:
import os
os.chdir(str(root))
self.assertIsNone(cypilot_root_from_project_config())
finally:
import os
os.chdir(str(cwd))
class TestLoadAdapterConfig(unittest.TestCase):
def test_load_adapter_config_reads_project_and_rules(self):
with TemporaryDirectory() as tmpdir:
ad = Path(tmpdir) / "adapter"
ad.mkdir()
(ad / "AGENTS.md").write_text("# Cypilot Adapter: MyProj\n", encoding="utf-8")
(ad / "config").mkdir()
(ad / "config" / "rules").mkdir()
(ad / "config" / "rules" / "a.md").write_text("# A\n", encoding="utf-8")
(ad / "config" / "rules" / "b.md").write_text("# B\n", encoding="utf-8")
cfg = load_adapter_config(ad)
self.assertEqual(cfg.get("project_name"), "MyProj")
self.assertEqual(cfg.get("rules"), ["a", "b"])
def test_load_adapter_config_without_rules_dir(self):
with TemporaryDirectory() as tmpdir:
ad = Path(tmpdir) / "adapter"
ad.mkdir()
(ad / "AGENTS.md").write_text("# Cypilot Adapter: MyProj\n", encoding="utf-8")
cfg = load_adapter_config(ad)
self.assertEqual(cfg.get("project_name"), "MyProj")
self.assertEqual(cfg.get("rules"), [])
def test_find_adapter_no_adapter(self):
"""Test when no adapter directory exists."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
# Create .git to mark as project root
(root / ".git").mkdir()
result = find_adapter_directory(root)
self.assertIsNone(result)
def test_find_adapter_with_rules_only(self):
"""Test finding adapter with rules/ directory only."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
# Create .git to mark as project root
(root / ".git").mkdir()
adapter_dir = root / ".cypilot-adapter"
adapter_dir.mkdir()
# Create AGENTS.md (required)
(adapter_dir / "AGENTS.md").write_text("# Navigation\n\nAdapter navigation.")
# Create rules directory (validates as adapter)
rules_dir = adapter_dir / "config" / "rules"
rules_dir.mkdir(parents=True)
(rules_dir / "api.md").write_text("# API")
result = find_adapter_directory(root)
self.assertIsNotNone(result)
self.assertEqual(result.resolve(), adapter_dir.resolve())
class TestIterRegistryEntries(unittest.TestCase):
def test_iter_registry_entries_with_artifacts_list(self):
registry = {"artifacts": [{"path": "a.md"}, {"path": "b.md"}]}
result = iter_registry_entries(registry)
self.assertEqual(len(result), 2)
self.assertEqual(result[0]["path"], "a.md")
def test_iter_registry_entries_missing_artifacts_returns_empty(self):
registry = {"systems": []}
result = iter_registry_entries(registry)
self.assertEqual(result, [])
def test_iter_registry_entries_artifacts_not_list_returns_empty(self):
registry = {"artifacts": "not-a-list"}
result = iter_registry_entries(registry)
self.assertEqual(result, [])
def test_iter_registry_entries_skips_non_dict_items(self):
registry = {"artifacts": [{"path": "a.md"}, "invalid", 123, {"path": "b.md"}]}
result = iter_registry_entries(registry)
self.assertEqual(len(result), 2)
class TestLoadArtifactsRegistryEdgeCases(unittest.TestCase):
def test_load_artifacts_registry_missing_systems_and_artifacts(self):
with TemporaryDirectory() as tmpdir:
ad = Path(tmpdir)
(ad / "artifacts.json").write_text('{"version": "1.0"}', encoding="utf-8")
reg, err = load_artifacts_registry(ad)
self.assertIsNone(reg)
self.assertIn("missing 'systems' or 'artifacts'", err)
class TestLoadAdapterConfigExceptionHandling(unittest.TestCase):
def test_load_adapter_config_agents_md_read_error(self):
"""Cover exception handling when reading AGENTS.md fails."""
with TemporaryDirectory() as tmpdir:
ad = Path(tmpdir) / "adapter"
ad.mkdir()
agents = ad / "AGENTS.md"
agents.write_text("# Cypilot Adapter: Test\n", encoding="utf-8")
orig = Path.read_text
def boom(self, *args, **kwargs):
if "AGENTS" in str(self):
raise OSError("boom")
return orig(self, *args, **kwargs)
try:
Path.read_text = boom # type: ignore
cfg = load_adapter_config(ad)
# Should still return config without project_name
self.assertIsInstance(cfg, dict)
self.assertNotIn("project_name", cfg)
finally:
Path.read_text = orig # type: ignore
class TestIsAdapterDirectoryContentBased(unittest.TestCase):
def test_adapter_with_spec_in_agents_content(self):
"""Cover content-based detection (spec keyword in AGENTS.md)."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
adapter_dir = root / "my-adapter"
adapter_dir.mkdir()
# AGENTS.md mentions "spec" but no specs/ directory
(adapter_dir / "AGENTS.md").write_text(
"# Cypilot Adapter: Test\n\nSee our spec documents.\n",
encoding="utf-8",
)
result = find_adapter_directory(root)
self.assertIsNotNone(result)
self.assertEqual(result.resolve(), adapter_dir.resolve())
def test_adapter_max_depth_exceeded_returns_none(self):
"""Cover max_depth limit in recursive search."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
# Create deeply nested adapter (beyond default max_depth of 5)
deep = root / "a" / "b" / "c" / "d" / "e" / "f" / "g" / "adapter"
deep.mkdir(parents=True)
(deep / "AGENTS.md").write_text("# Cypilot Adapter: Deep\n", encoding="utf-8")
(deep / "specs").mkdir()
result = find_adapter_directory(root)
self.assertIsNone(result)
class TestCypilotRootFromProjectConfigEdgeCases(unittest.TestCase):
def test_cypilot_root_no_project_root_returns_none(self):
"""Cover cypilot_root_from_project_config returning None when no project root."""
with TemporaryDirectory() as tmpdir:
# No .git or .cypilot-config.json - no project root
cwd = Path.cwd()
try:
import os
os.chdir(tmpdir)
result = cypilot_root_from_project_config()
self.assertIsNone(result)
finally:
os.chdir(str(cwd))
def test_cypilot_root_no_config_returns_none(self):
"""Cover cypilot_root_from_project_config returning None when config missing."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir() # Project root exists but no config
cwd = Path.cwd()
try:
import os
os.chdir(str(root))
result = cypilot_root_from_project_config()
self.assertIsNone(result)
finally:
os.chdir(str(cwd))
if __name__ == "__main__":
unittest.main()