-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_commandgraph.py
More file actions
7176 lines (6334 loc) · 275 KB
/
test_commandgraph.py
File metadata and controls
7176 lines (6334 loc) · 275 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
"""
Comprehensive test suite for CommandGraph (cgr).
Covers: lexer, both parsers (.cg and .cgr), resolver, state tracking,
output collection, variable expansion, tags, when expressions, diff,
templates, inventory parsing, version checking, redaction, and execution.
Run: python3 -m pytest test_commandgraph.py -v
(Engine file: cgr.py)
"""
from __future__ import annotations
import argparse
import importlib.util
import io
import json
import os
import shlex
import socket
import subprocess
import sys
import tempfile
import threading
import time
import textwrap
import unittest
import urllib.request
from pathlib import Path
import pytest
# ── Import engine ────────────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).parent))
import build_helpers
import cgr as cg
# ══════════════════════════════════════════════════════════════════════════════
# Helpers
# ══════════════════════════════════════════════════════════════════════════════
def _resolve_cgr(source: str, repo_dir=None, extra_vars=None, inventory_files=None,
resolve_deferred_secrets: bool = False) -> cg.Graph:
"""Parse .cgr source and resolve into a Graph."""
ast = cg.parse_cgr(source)
return cg.resolve(ast, repo_dir=repo_dir, extra_vars=extra_vars,
inventory_files=inventory_files,
resolve_deferred_secrets=resolve_deferred_secrets)
def _resolve_cg(source: str, repo_dir=None, extra_vars=None) -> cg.Graph:
"""Parse .cg source and resolve into a Graph."""
tokens = cg.lex(source)
ast = cg.Parser(tokens, source, "<test>").parse()
return cg.resolve(ast, repo_dir=repo_dir, extra_vars=extra_vars)
def _tmpfile(content: str, suffix=".cgr") -> str:
"""Write content to a temp file and return its path."""
f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix, delete=False)
f.write(content)
f.close()
return f.name
def _write_encrypted_secrets(path: Path, passphrase: str, pairs: dict[str, str]) -> None:
plaintext = "\n".join(f'{k} = "{v}"' for k, v in pairs.items()) + "\n"
path.write_bytes(cg._encrypt_data(plaintext.encode(), passphrase))
def _write_legacy_encrypted_secrets(path: Path, passphrase: str, pairs: dict[str, str]) -> None:
plaintext = "\n".join(f'{k} = "{v}"' for k, v in pairs.items()) + "\n"
salt = os.urandom(16)
key = cg._derive_key(passphrase, salt)
iv = os.urandom(16)
proc = subprocess.run(
["openssl", "enc", "-aes-256-cbc", "-nosalt", "-K", key.hex(), "-iv", iv.hex()],
input=plaintext.encode(),
capture_output=True,
check=True,
)
path.write_bytes(b"CGRSECRT" + salt + iv + proc.stdout)
def _load_module_from_path(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
# ══════════════════════════════════════════════════════════════════════════════
# §1 LEXER
# ══════════════════════════════════════════════════════════════════════════════
class TestLexer:
def test_basic_tokens(self):
tokens = cg.lex('var name = "hello"')
types = [t.type for t in tokens]
assert cg.TT.IDENT in types
assert cg.TT.EQUALS in types
assert cg.TT.STRING in types
assert tokens[-1].type == cg.TT.EOF
def test_command_token(self):
tokens = cg.lex('`echo hello`')
assert any(t.type == cg.TT.COMMAND and t.value == "echo hello" for t in tokens)
def test_string_escapes(self):
tokens = cg.lex(r'"hello\nworld"')
s = [t for t in tokens if t.type == cg.TT.STRING][0]
assert "\n" in s.value
def test_comments_ignored(self):
tokens = cg.lex('# this is a comment\nvar x = "1"')
assert not any(t.value == "this" for t in tokens)
def test_number_token(self):
tokens = cg.lex('123')
assert any(t.type == cg.TT.NUMBER and t.value == "123" for t in tokens)
def test_gte_operator(self):
tokens = cg.lex('>= 1')
assert any(t.type == cg.TT.GTE for t in tokens)
def test_compat_operator(self):
tokens = cg.lex('~> 2')
assert any(t.type == cg.TT.COMPAT for t in tokens)
def test_dot_token(self):
tokens = cg.lex('a.b')
assert any(t.type == cg.TT.DOT for t in tokens)
def test_unterminated_string_raises(self):
with pytest.raises(cg.LexError):
cg.lex('"hello')
def test_unterminated_command_raises(self):
with pytest.raises(cg.LexError):
cg.lex('`echo')
def test_unexpected_char_raises(self):
with pytest.raises(cg.LexError):
cg.lex('@')
def test_line_numbers(self):
tokens = cg.lex('var x = "1"\nvar y = "2"')
y_tok = [t for t in tokens if t.value == "y"][0]
assert y_tok.line == 2
# ══════════════════════════════════════════════════════════════════════════════
# §3b CGR PARSER
# ══════════════════════════════════════════════════════════════════════════════
class TestCGRParser:
def test_minimal_graph(self):
src = textwrap.dedent('''\
target "local" local:
[say hello]:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert len(ast.nodes) == 1
assert ast.nodes[0].name == "local"
assert len(ast.nodes[0].resources) == 1
# Parser slugifies names
assert ast.nodes[0].resources[0].name == "say_hello"
def test_title_comment(self):
src = textwrap.dedent('''\
--- My Title ---
target "local" local:
[step]:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert len(ast.nodes) == 1
def test_variables(self):
src = textwrap.dedent('''\
set port = "8080"
set host = "localhost"
target "local" local:
[step]:
run $ echo ${port}
''')
ast = cg.parse_cgr(src)
assert len(ast.variables) == 2
assert ast.variables[0].name == "port"
assert ast.variables[0].value == "8080"
def test_dependency(self):
src = textwrap.dedent('''\
target "local" local:
[step a]:
run $ echo a
[step b]:
first [step a]
run $ echo b
''')
ast = cg.parse_cgr(src)
step_b = ast.nodes[0].resources[1]
# Parser slugifies dependency names
assert "step_a" in step_b.needs
def test_skip_if(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
skip if $ test -f /tmp/done
run $ touch /tmp/done
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].check == "test -f /tmp/done"
def test_always_run(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
always run $ echo hi
''')
ast = cg.parse_cgr(src)
r = ast.nodes[0].resources[0]
assert r.check == "false"
assert r.run == "echo hi"
def test_as_root(self):
src = textwrap.dedent('''\
target "local" local:
[step] as root:
run $ whoami
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].run_as == "root"
def test_step_header_missing_colon_raises(self):
src = textwrap.dedent('''\
target "local" local:
[step a]:
run $ echo a
[step b]
first [step a]
run $ echo b
''')
with pytest.raises(cg.CGRParseError, match=r"Invalid step header"):
cg.parse_cgr(src)
def test_timeout_and_retry(self):
src = textwrap.dedent('''\
target "local" local:
[step] timeout 30s, retry 3x:
run $ echo hi
''')
ast = cg.parse_cgr(src)
r = ast.nodes[0].resources[0]
assert r.timeout == 30
assert r.retries == 3
def test_timeout_minutes(self):
src = textwrap.dedent('''\
target "local" local:
[step] timeout 2m:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].timeout == 120
def test_timeout_reset_on_output_cgr(self):
src = textwrap.dedent('''\
target "local" local:
[step] timeout 30s reset on output:
run $ echo hi
''')
ast = cg.parse_cgr(src)
r = ast.nodes[0].resources[0]
assert r.timeout == 30
assert r.timeout_reset_on_output is True
def test_timeout_reset_on_output_cg(self):
src = textwrap.dedent('''\
node "local" {
via local
resource step {
timeout 30 reset on output
run `echo hi`
}
}
''')
ast = cg.Parser(cg.lex(src), src, "<test>").parse()
r = ast.nodes[0].resources[0]
assert r.timeout == 30
assert r.timeout_reset_on_output is True
def test_timeout_hours(self):
src = textwrap.dedent("""\
target "local" local:
[step] timeout 2h:
run $ echo hi
""")
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].timeout == 7200
def test_retry_delay_hours(self):
src = textwrap.dedent("""\
target "local" local:
[step] retry 3x wait 1h:
run $ echo hi
""")
ast = cg.parse_cgr(src)
r = ast.nodes[0].resources[0]
assert r.retries == 3
assert r.retry_delay == 3600
def test_body_timeout_hours(self):
src = textwrap.dedent("""\
target "local" local:
[step]:
timeout 1h
run $ echo hi
""")
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].timeout == 3600
def test_verify_block(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ echo hi
verify "it works":
first [step]
run $ echo ok
retry 3x wait 2s
''')
ast = cg.parse_cgr(src)
verify = [r for r in ast.nodes[0].resources if r.is_verify]
assert len(verify) == 1
assert verify[0].retries == 3
assert verify[0].retry_delay == 2
def test_verify_block_multiline_run_and_timeout(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ echo hi
verify "it works":
first [step]
run $ cd /tmp && \\
((echo one || \\
echo two) | wc -l | grep -q '^1$')
retry 5x wait 5s
timeout 60m reset on output
''')
ast = cg.parse_cgr(src)
verify = [r for r in ast.nodes[0].resources if r.is_verify]
assert len(verify) == 1
assert verify[0].run.startswith("cd /tmp && \\")
assert "echo one || \\" in verify[0].run
assert "echo two" in verify[0].run
assert "grep -q '^1$')" in verify[0].run
assert verify[0].run.count("\n") == 2
assert verify[0].retries == 5
assert verify[0].retry_delay == 5
assert verify[0].timeout == 3600
assert verify[0].timeout_reset_on_output is True
def test_if_fails_warn(self):
src = textwrap.dedent('''\
target "local" local:
[step] if fails warn:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].on_fail == "warn"
def test_when_clause(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
when os_family == "debian"
run $ apt-get update
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].when == 'os_family == "debian"'
def test_when_unquoted(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
when debug
run $ echo debug
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].when == "debug"
def test_tags(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
tags web, deploy
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].tags == ["web", "deploy"]
def test_collect(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ hostname
collect "hostname"
''')
ast = cg.parse_cgr(src)
assert ast.nodes[0].resources[0].collect_key == "hostname"
def test_ssh_target(self):
src = textwrap.dedent('''\
target "web" ssh deploy@10.0.1.5:
[step]:
run $ uptime
''')
ast = cg.parse_cgr(src)
node = ast.nodes[0]
assert node.via.method == "ssh"
assert node.via.props.get("host") == "10.0.1.5"
assert node.via.props.get("user") == "deploy"
def test_using_import(self):
src = textwrap.dedent('''\
using apt/install_package
target "local" local:
[step]:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert len(ast.uses) == 1
assert ast.uses[0].path == "apt/install_package"
def test_using_with_version_constraint(self):
src = textwrap.dedent('''\
using apt/install_package >= 1.0
target "local" local:
[step]:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert ast.uses[0].path == "apt/install_package"
assert ast.uses[0].version_op == ">="
assert ast.uses[0].version_req == "1.0"
def test_secrets_declaration(self):
src = textwrap.dedent('''\
secrets "vault.enc"
target "local" local:
[step]:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert len(ast.secrets) == 1
assert ast.secrets[0].path == "vault.enc"
def test_inventory_declaration(self):
src = textwrap.dedent('''\
inventory "hosts.ini"
target "local" local:
[step]:
run $ echo hi
''')
ast = cg.parse_cgr(src)
assert len(ast.inventories) == 1
assert ast.inventories[0].path == "hosts.ini"
def test_multiple_first_on_one_line(self):
src = textwrap.dedent('''\
target "local" local:
[a]:
run $ echo a
[b]:
run $ echo b
[c]:
first [a] [b]
run $ echo c
''')
ast = cg.parse_cgr(src)
step_c = ast.nodes[0].resources[2]
assert "a" in step_c.needs
assert "b" in step_c.needs
def test_parallel_block(self):
src = textwrap.dedent('''\
target "local" local:
[build]:
parallel 2 at a time:
[frontend]:
run $ echo front
[backend]:
run $ echo back
''')
ast = cg.parse_cgr(src)
build = ast.nodes[0].resources[0]
assert build.parallel_limit == 2
assert len(build.parallel_block) == 2
def test_race_block(self):
src = textwrap.dedent('''\
target "local" local:
[fetch]:
race:
[mirror1]:
run $ echo m1
[mirror2]:
run $ echo m2
''')
ast = cg.parse_cgr(src)
fetch = ast.nodes[0].resources[0]
assert len(fetch.race_block) == 2
def test_each_block(self):
src = textwrap.dedent('''\
set servers = "a,b,c"
target "local" local:
[deploy]:
each server in ${servers}, 2 at a time:
[deploy ${server}]:
run $ echo ${server}
''')
ast = cg.parse_cgr(src)
deploy = ast.nodes[0].resources[0]
assert deploy.each_var == "server"
assert deploy.each_limit == 2
def test_cross_node_dependency(self):
src = textwrap.dedent('''\
target "db" local:
[setup schema]:
run $ echo schema
target "web" local, after "db":
[deploy]:
first [db/setup schema]
run $ echo deploy
''')
ast = cg.parse_cgr(src)
web = ast.nodes[1]
assert "db" in web.after_nodes
deploy = web.resources[0]
# Cross-node refs use dot notation internally: "db.setup_schema"
assert "db.setup_schema" in deploy.needs
def test_wait_for_webhook(self):
src = textwrap.dedent("""\
target "local" local:
[wait for approval]:
wait for webhook '/approve/${deploy_id}'
timeout 4h
""")
ast = cg.parse_cgr(src)
res = ast.nodes[0].resources[0]
assert res.wait_kind == "webhook"
assert res.wait_target == "/approve/${deploy_id}"
assert res.timeout == 14400
def test_subgraph_step(self):
src = textwrap.dedent("""\
target "local" local:
[deploy app] from ./deploy_app.cgr:
version = '2.1.0'
""")
ast = cg.parse_cgr(src)
res = ast.nodes[0].resources[0]
assert res.subgraph_path == "./deploy_app.cgr"
assert res.subgraph_vars == {"version": "2.1.0"}
def test_parse_error_on_invalid(self):
with pytest.raises(cg.CGRParseError):
cg.parse_cgr("this is not valid cgr")
# ══════════════════════════════════════════════════════════════════════════════
# §3 .CG PARSER
# ══════════════════════════════════════════════════════════════════════════════
class TestCGParser:
def test_minimal_graph(self):
src = textwrap.dedent('''\
node "local" {
via local
resource step {
run `echo hi`
}
}
''')
graph = _resolve_cg(src)
assert len(graph.all_resources) == 1
def test_variables(self):
src = textwrap.dedent('''\
var port = "8080"
node "local" {
via local
resource step {
run `echo ${port}`
}
}
''')
graph = _resolve_cg(src)
assert "8080" in graph.all_resources[list(graph.all_resources)[0]].run
def test_dependencies(self):
src = textwrap.dedent('''\
node "local" {
via local
resource a {
run `echo a`
}
resource b {
needs a
run `echo b`
}
}
''')
graph = _resolve_cg(src)
b = [r for r in graph.all_resources.values() if r.short_name == "b"][0]
assert len(b.needs) > 0
def test_check_clause(self):
src = textwrap.dedent('''\
node "local" {
via local
resource step {
check `test -f /tmp/x`
run `touch /tmp/x`
}
}
''')
graph = _resolve_cg(src)
step = list(graph.all_resources.values())[0]
assert step.check == "test -f /tmp/x"
def test_tags_in_cg(self):
src = textwrap.dedent('''\
node "local" {
via local
resource step {
tags web, deploy
run `echo hi`
}
}
''')
graph = _resolve_cg(src)
step = list(graph.all_resources.values())[0]
assert "web" in step.tags
assert "deploy" in step.tags
# ══════════════════════════════════════════════════════════════════════════════
# §5 RESOLVER
# ══════════════════════════════════════════════════════════════════════════════
class TestResolver:
def test_single_step(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ echo hi
''')
graph = _resolve_cgr(src)
assert len(graph.all_resources) == 1
assert len(graph.waves) == 1
def test_dependency_ordering(self):
"""Steps with dependencies are in later waves."""
src = textwrap.dedent('''\
target "local" local:
[a]:
run $ echo a
[b]:
first [a]
run $ echo b
[c]:
first [b]
run $ echo c
''')
graph = _resolve_cgr(src)
assert len(graph.waves) == 3
# a in wave 0, b in wave 1, c in wave 2
a_id = [r.id for r in graph.all_resources.values() if r.short_name == "a"][0]
b_id = [r.id for r in graph.all_resources.values() if r.short_name == "b"][0]
c_id = [r.id for r in graph.all_resources.values() if r.short_name == "c"][0]
assert a_id in graph.waves[0]
assert b_id in graph.waves[1]
assert c_id in graph.waves[2]
def test_parallel_waves(self):
"""Independent steps are in the same wave."""
src = textwrap.dedent('''\
target "local" local:
[a]:
run $ echo a
[b]:
run $ echo b
[c]:
first [a]
first [b]
run $ echo c
''')
graph = _resolve_cgr(src)
assert len(graph.waves) == 2 # a+b in wave 0, c in wave 1
assert len(graph.waves[0]) == 2
def test_variable_expansion(self):
src = textwrap.dedent('''\
set greeting = "hello"
target "local" local:
[step]:
run $ echo ${greeting}
''')
graph = _resolve_cgr(src)
step = list(graph.all_resources.values())[0]
assert "hello" in step.run
def test_variable_override(self):
src = textwrap.dedent('''\
set port = "8080"
target "local" local:
[step]:
run $ echo ${port}
''')
graph = _resolve_cgr(src, extra_vars={"port": "9090"})
step = list(graph.all_resources.values())[0]
assert "9090" in step.run
def test_undefined_variable_raises(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ echo ${undefined_var}
''')
with pytest.raises(cg.ResolveError, match="Undefined variable"):
_resolve_cgr(src)
def test_cycle_detection(self):
src = textwrap.dedent('''\
target "local" local:
[a]:
first [b]
run $ echo a
[b]:
first [a]
run $ echo b
''')
with pytest.raises(cg.ResolveError, match="[Cc]ycle"):
_resolve_cgr(src)
def test_deduplication(self):
"""Identical check+run+run_as on the same node should dedup."""
src = textwrap.dedent('''\
target "local" local:
[step a]:
skip if $ test -f /tmp/x
run $ touch /tmp/x
[step b]:
skip if $ test -f /tmp/x
run $ touch /tmp/x
''')
graph = _resolve_cgr(src)
# Should deduplicate to 1 resource
non_barrier = [r for r in graph.all_resources.values() if not r.is_barrier]
assert len(non_barrier) == 1
def test_no_cross_node_dedup(self):
"""Same command on different nodes should NOT dedup."""
src = textwrap.dedent('''\
target "node1" local:
[step]:
run $ echo hi
target "node2" local:
[step]:
run $ echo hi
''')
graph = _resolve_cgr(src)
non_barrier = [r for r in graph.all_resources.values() if not r.is_barrier]
assert len(non_barrier) == 2
def test_verify_is_marked(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ echo hi
verify "works":
first [step]
run $ echo ok
''')
graph = _resolve_cgr(src)
verify = [r for r in graph.all_resources.values() if r.is_verify]
assert len(verify) == 1
def test_parallel_expansion(self):
"""Parallel block expands into children + barrier (parent becomes barrier)."""
src = textwrap.dedent('''\
target "local" local:
[build]:
parallel:
[a]:
run $ echo a
[b]:
run $ echo b
''')
graph = _resolve_cgr(src)
# a + b + build (barrier joining them) = 3
assert len(graph.all_resources) == 3
# build should be a barrier
build = [r for r in graph.all_resources.values() if r.short_name == "build"][0]
assert build.is_barrier is True
def test_each_expansion(self):
"""Each block expands into N resources."""
src = textwrap.dedent('''\
set items = "x,y,z"
target "local" local:
[process]:
each item in ${items}:
[do ${item}]:
run $ echo ${item}
''')
graph = _resolve_cgr(src)
names = [r.short_name for r in graph.all_resources.values()]
# Variable name is 'item', values are x/y/z → slugs: do_item_x, etc.
assert any("x" in n for n in names)
assert any("y" in n for n in names)
assert any("z" in n for n in names)
def test_race_expansion(self):
"""Race block produces is_race resources."""
src = textwrap.dedent('''\
target "local" local:
[fetch]:
race:
[a]:
run $ echo a
[b]:
run $ echo b
''')
graph = _resolve_cgr(src)
race_res = [r for r in graph.all_resources.values() if r.is_race]
assert len(race_res) == 2
def test_cross_node_dependency(self):
src = textwrap.dedent('''\
target "db" local:
[setup]:
run $ echo db
target "web" local, after "db":
[deploy]:
first [db/setup]
run $ echo web
''')
graph = _resolve_cgr(src)
deploy = [r for r in graph.all_resources.values() if r.short_name == "deploy"][0]
# deploy should depend on db's setup (through barriers)
assert len(deploy.needs) > 0
def test_tags_preserved(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
tags security, web
run $ echo hi
''')
graph = _resolve_cgr(src)
step = [r for r in graph.all_resources.values() if not r.is_barrier][0]
assert "security" in step.tags
assert "web" in step.tags
def test_when_preserved(self):
src = textwrap.dedent('''\
set os = "debian"
target "local" local:
[step]:
when os == "debian"
run $ echo hi
''')
graph = _resolve_cgr(src)
step = list(graph.all_resources.values())[0]
assert step.when is not None
def test_collect_key_preserved(self):
src = textwrap.dedent('''\
target "local" local:
[step]:
run $ hostname
collect "hostname"
''')
graph = _resolve_cgr(src)
step = list(graph.all_resources.values())[0]
assert step.collect_key == "hostname"
# ══════════════════════════════════════════════════════════════════════════════
# Templates
# ══════════════════════════════════════════════════════════════════════════════
class TestTemplates:
"""Test template loading and expansion using the actual repo/ directory."""
@pytest.fixture
def repo_dir(self):
return str(Path(__file__).parent / "repo")
def test_template_expansion(self, repo_dir):
src = textwrap.dedent('''\
using apt/install_package
target "local" local:
[install curl] from apt/install_package:
name = "curl"
''')
graph = _resolve_cgr(src, repo_dir=repo_dir)
# Should have expanded: update_cache + install step
assert len(graph.all_resources) >= 2
def test_template_dedup(self, repo_dir):
"""Two calls to install_package should share update_cache."""
src = textwrap.dedent('''\
using apt/install_package
target "local" local:
[install curl] from apt/install_package:
name = "curl"
[install wget] from apt/install_package:
name = "wget"
''')
graph = _resolve_cgr(src, repo_dir=repo_dir)
assert len(graph.dedup_map) > 0 # at least one dedup happened
def test_template_multi_package(self, repo_dir):
src = textwrap.dedent('''\
using apt/install_package
target "local" local:
[install curl and wget] from apt/install_package:
name = "curl wget"
''')
graph = _resolve_cgr(src, repo_dir=repo_dir)
res = graph.all_resources["local.install_curl_and_wget"]
assert "apt-get install -y" in res.run
assert "curl" in res.run
assert "wget" in res.run
assert 'for pkg in curl wget' in res.check
def test_template_version_check(self, repo_dir):
src = textwrap.dedent('''\
using apt/install_package >= 1.0
target "local" local:
[install curl] from apt/install_package:
name = "curl"
''')
# Should resolve without error (stdlib is v1.0.0)
graph = _resolve_cgr(src, repo_dir=repo_dir)
assert len(graph.all_resources) >= 2
def test_template_provenance(self, repo_dir):
src = textwrap.dedent('''\
using apt/install_package
target "local" local:
[install curl] from apt/install_package:
name = "curl"
''')
graph = _resolve_cgr(src, repo_dir=repo_dir)
assert len(graph.provenance_log) > 0
def test_template_composition_in_template_body(self, tmp_path):
repo = tmp_path / "repo"
(repo / "apt").mkdir(parents=True)
(repo / "stack").mkdir(parents=True)
(repo / "apt" / "install_package.cgr").write_text(textwrap.dedent("""\
template install_package(name):
[install ${name}]:
run $ echo install ${name}
"""))
(repo / "stack" / "setup_webserver.cgr").write_text(textwrap.dedent("""\
template setup_webserver(domain, package = "nginx"):
[install web package] from apt/install_package:
name = "${package}"
[get cert]:
run $ echo cert ${domain}
first [install web package]
"""))
src = textwrap.dedent("""\
using apt/install_package
using stack/setup_webserver
target "local" local:
[setup site] from stack/setup_webserver:
domain = "example.com"
""")
graph = _resolve_cgr(src, repo_dir=str(repo))
install = graph.all_resources["local.install_web_package"]
install_leaf_id = next(rid for rid in graph.all_resources if rid.startswith("local.install_web_package.") and graph.all_resources[rid].run)
install_leaf = graph.all_resources[install_leaf_id]
cert_id = next(rid for rid in graph.all_resources if rid.endswith(".get_cert"))
cert = graph.all_resources[cert_id]
assert install_leaf.run == "echo install nginx"
assert install.id in cert.needs