-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_make.py
More file actions
1222 lines (1034 loc) · 49 KB
/
Copy pathtest_make.py
File metadata and controls
1222 lines (1034 loc) · 49 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
"""Unit + dry-run integration tests for make.py.
Two layers:
1. **Unit tests** — import make.py directly and exercise pure logic
(Versions, Platform, _winquote, Runner, etc.). No subprocess, no
network, no filesystem mutation outside pytest's tmp_path.
2. **Dry-run snapshot tests** — spawn `python3 make.py --dry-run <args>`
and assert the printed command sequence. Canonical contract test
for "the orchestrator still emits the right cmake/ctest/buf calls."
Subprocess tests use `--dry-run`, so they never touch the toolchain or
network. The whole suite runs in ~5s on any host.
Run:
pip install pytest
python -m pytest test_make.py -v
"""
import json
import subprocess
import sys
from pathlib import Path
import pytest
import make
REPO_ROOT = Path(__file__).resolve().parent
MAKE_PY = REPO_ROOT / "make.py"
# ---------------------------------------------------------------------------
# Unit: Versions
# ---------------------------------------------------------------------------
class TestVersions:
def test_loads_real_versions_env(self):
v = make.Versions.load(REPO_ROOT)
# Every key documented in versions.env must be present.
for key in (
"GO_VERSION",
"BUF_VERSION",
"DEFAULT_VARIANT",
"MODERN_PROTOBUF_VERSION",
"MODERN_VCPKG_BASELINE_COMMIT",
"LEGACY_V3_PROTOBUF_VERSION",
"LEGACY_V3_VCPKG_BASELINE_COMMIT",
"DOTNET_VERSION",
"CMAKE_VERSION",
):
assert key in v.raw, f"Expected {key} in versions.env"
assert v.raw[key], f"{key} must not be empty"
def test_typed_accessors(self):
v = make.Versions.load(REPO_ROOT)
assert v.go_version == v.raw["GO_VERSION"]
assert v.buf_version == v.raw["BUF_VERSION"]
assert v.dotnet_version == v.raw["DOTNET_VERSION"]
assert v.cmake_version == v.raw["CMAKE_VERSION"]
# default_variant is lowercased.
assert v.default_variant == v.raw["DEFAULT_VARIANT"].lower()
# protobuf_version / vcpkg_baseline_commit resolve through DEFAULT_VARIANT
# to the corresponding MODERN_/LEGACY_V3_-prefixed key.
prefix = v.default_variant.upper().replace("-", "_")
assert v.protobuf_version == v.raw[f"{prefix}_PROTOBUF_VERSION"]
assert v.vcpkg_baseline_commit == v.raw[f"{prefix}_VCPKG_BASELINE_COMMIT"]
def test_variants_enumerates_all_rows(self):
v = make.Versions.load(REPO_ROOT)
variants = v.variants()
# Both rows declared in versions.env must be present and complete.
assert "modern" in variants
assert "legacy_v3" in variants
for label, row in variants.items():
assert row.get("protobuf_version"), f"{label} missing protobuf_version"
assert row.get("vcpkg_baseline_commit"), f"{label} missing vcpkg_baseline_commit"
def test_default_variant_falls_back_to_modern(self):
# Old versions.env files without DEFAULT_VARIANT default to 'modern'.
v = make.Versions(raw={})
assert v.default_variant == "modern"
def test_variant_value_falls_back_to_unprefixed_key(self):
# Backward compat: a flat versions.env (legacy schema) still resolves.
v = make.Versions(raw={"PROTOBUF_VERSION": "9.9.9", "VCPKG_BASELINE_COMMIT": "f" * 40})
assert v.protobuf_version == "9.9.9"
assert v.vcpkg_baseline_commit == "f" * 40
def test_default_variant_label_with_dash_resolves(self):
# 'legacy-v3' (CI label form) and 'legacy_v3' (env-key form) both work.
v = make.Versions(raw={
"DEFAULT_VARIANT": "legacy-v3",
"LEGACY_V3_PROTOBUF_VERSION": "3.21.12",
"LEGACY_V3_VCPKG_BASELINE_COMMIT": "a" * 40,
})
assert v.protobuf_version == "3.21.12"
assert v.vcpkg_baseline_commit == "a" * 40
def test_protobuf_version_looks_like_semver(self):
v = make.Versions.load(REPO_ROOT)
# Cheap smoke check — guards against a typo that breaks vcpkg.
parts = v.protobuf_version.split(".")
assert 2 <= len(parts) <= 3
for p in parts:
assert p.isdigit(), f"Non-numeric protobuf version segment: {p}"
def test_vcpkg_baseline_is_full_sha(self):
v = make.Versions.load(REPO_ROOT)
assert len(v.vcpkg_baseline_commit) == 40
int(v.vcpkg_baseline_commit, 16) # raises ValueError if not hex
def test_ignores_blank_and_comment_lines(self, tmp_path):
env = tmp_path / ".devcontainer"
env.mkdir()
(env / "versions.env").write_text(
"\n"
"# this is a comment\n"
"FOO=bar\n"
"\n"
"# another comment\n"
"BAZ=qux\n",
encoding="utf-8",
)
v = make.Versions.load(tmp_path)
assert v.raw == {"FOO": "bar", "BAZ": "qux"}
def test_missing_file_raises(self, tmp_path):
with pytest.raises(FileNotFoundError):
make.Versions.load(tmp_path)
def test_get_with_default(self):
v = make.Versions(raw={"FOO": "bar"})
assert v.get("FOO") == "bar"
assert v.get("MISSING") is None
assert v.get("MISSING", "default") == "default"
# ---------------------------------------------------------------------------
# Unit: Platform
# ---------------------------------------------------------------------------
class TestPlatform:
def test_detect_returns_one_os(self):
p = make.Platform.detect()
# Exactly one of is_windows / is_macos / is_linux must be True.
flags = [p.is_windows, p.is_macos, p.is_linux]
assert sum(flags) == 1, f"Expected exactly one OS flag, got {flags}"
def test_vcpkg_triplet_windows(self):
p = make.Platform(sys_platform="win32", machine="amd64", in_devcontainer=False)
assert p.vcpkg_triplet == "x64-windows-static"
def test_vcpkg_triplet_macos_x64(self):
p = make.Platform(
sys_platform="darwin", machine="x86_64", in_devcontainer=False
)
assert p.vcpkg_triplet == "x64-osx"
def test_vcpkg_triplet_macos_arm64(self):
p = make.Platform(sys_platform="darwin", machine="arm64", in_devcontainer=False)
assert p.vcpkg_triplet == "arm64-osx"
def test_vcpkg_triplet_linux_x64(self):
p = make.Platform(sys_platform="linux", machine="x86_64", in_devcontainer=False)
assert p.vcpkg_triplet == "x64-linux"
def test_vcpkg_triplet_linux_arm64(self):
p = make.Platform(
sys_platform="linux", machine="aarch64", in_devcontainer=False
)
assert p.vcpkg_triplet == "arm64-linux"
def test_cmake_toolchain_args_devcontainer_is_empty(self):
p = make.Platform(sys_platform="linux", machine="x86_64", in_devcontainer=True)
assert p.cmake_toolchain_args() == []
def test_cmake_toolchain_args_linux_no_vcpkg_is_empty(self, monkeypatch):
# Without vcpkg installed (no VCPKG_ROOT), cmake falls back to
# system protobuf via find_package — no -D flags needed.
monkeypatch.delenv("VCPKG_ROOT", raising=False)
p = make.Platform(sys_platform="linux", machine="x86_64", in_devcontainer=False)
assert p.cmake_toolchain_args() == []
def test_cmake_toolchain_args_linux_with_vcpkg_emits_flags(self, tmp_path):
# After `make.py setup --lang cpp` populates ~/vcpkg, native Linux
# builds also route through vcpkg. Same protobuf pin as Windows.
p = make.Platform(
sys_platform="linux",
machine="x86_64",
in_devcontainer=False,
vcpkg_root=tmp_path,
)
args = p.cmake_toolchain_args()
assert any("CMAKE_TOOLCHAIN_FILE" in a for a in args)
assert any("VCPKG_TARGET_TRIPLET=x64-linux" in a for a in args)
def test_cmake_toolchain_args_macos_no_vcpkg_is_empty(self, monkeypatch):
monkeypatch.delenv("VCPKG_ROOT", raising=False)
p = make.Platform(sys_platform="darwin", machine="arm64", in_devcontainer=False)
assert p.cmake_toolchain_args() == []
def test_cmake_toolchain_args_macos_with_vcpkg_emits_flags(self, tmp_path):
p = make.Platform(
sys_platform="darwin",
machine="arm64",
in_devcontainer=False,
vcpkg_root=tmp_path,
)
args = p.cmake_toolchain_args()
assert any("CMAKE_TOOLCHAIN_FILE" in a for a in args)
assert any("VCPKG_TARGET_TRIPLET=arm64-osx" in a for a in args)
def test_cmake_toolchain_args_windows_with_vcpkg_root(self, tmp_path):
p = make.Platform(
sys_platform="win32",
machine="amd64",
in_devcontainer=False,
vcpkg_root=tmp_path,
)
args = p.cmake_toolchain_args()
assert any("CMAKE_TOOLCHAIN_FILE" in a for a in args)
assert any("VCPKG_TARGET_TRIPLET=x64-windows-static" in a for a in args)
# Path must include vcpkg.cmake.
toolchain_arg = next(a for a in args if "CMAKE_TOOLCHAIN_FILE" in a)
assert toolchain_arg.endswith("vcpkg.cmake")
def test_cmake_toolchain_args_windows_explicit_triplet(self, tmp_path):
p = make.Platform(
sys_platform="win32",
machine="amd64",
in_devcontainer=False,
vcpkg_root=tmp_path,
)
args = p.cmake_toolchain_args(triplet="x64-windows")
assert any("VCPKG_TARGET_TRIPLET=x64-windows" in a for a in args)
assert not any("VCPKG_TARGET_TRIPLET=x64-windows-static" in a for a in args)
def test_cmake_toolchain_args_windows_no_vcpkg_root_returns_empty(
self, monkeypatch
):
# No VCPKG_ROOT in env, no vcpkg_root attr -> empty list (lets cmake
# fail with a useful "Could not find Protobuf" error).
monkeypatch.delenv("VCPKG_ROOT", raising=False)
p = make.Platform(sys_platform="win32", machine="amd64", in_devcontainer=False)
assert p.cmake_toolchain_args() == []
def test_detect_ignores_dockerenv_marker(self, monkeypatch):
"""Bug fix: /.dockerenv is created by Docker for *every* container,
not just the loader devcontainer. The detect() heuristic must NOT
treat its presence as a devcontainer signal."""
# Simulate: only /.dockerenv exists; /opt/vcpkg/active does NOT.
# Use as_posix() so the literal compares correctly on Windows where
# str(WindowsPath('/.dockerenv')) renders with backslashes.
def fake_exists(self):
return self.as_posix() == "/.dockerenv"
monkeypatch.setattr(make.Path, "exists", fake_exists)
p = make.Platform.detect()
assert p.in_devcontainer is False, (
"/.dockerenv alone must NOT be treated as devcontainer"
)
def test_detect_recognizes_vcpkg_active_marker(self, monkeypatch):
"""Positive: /opt/vcpkg/active is the marker the devcontainer's
Dockerfile actually sets. Its presence is the sole devcontainer signal."""
def fake_exists(self):
return self.as_posix() == "/opt/vcpkg/active"
monkeypatch.setattr(make.Path, "exists", fake_exists)
p = make.Platform.detect()
assert p.in_devcontainer is True
# ---------------------------------------------------------------------------
# Unit: Platform.windows_msvc_wrap
# ---------------------------------------------------------------------------
class TestWindowsMsvcWrap:
"""Exercises the central insight of make.py: the cmd-shell-string
sentinel that bypasses Python's CreateProcess quoting on Windows."""
def test_passthrough_on_linux(self):
p = make.Platform(sys_platform="linux", machine="x86_64", in_devcontainer=False)
cmd = ["cmake", "-S", ".", "-B", "build"]
assert p.windows_msvc_wrap(cmd) == cmd
def test_passthrough_on_macos(self):
p = make.Platform(sys_platform="darwin", machine="arm64", in_devcontainer=False)
cmd = ["cmake", "-S", ".", "-B", "build"]
assert p.windows_msvc_wrap(cmd) == cmd
def test_windows_with_no_vcvarsall_returns_unchanged(self):
# When MSVC isn't installed, return cmd unchanged so subprocess
# fails with a useful "cl.exe not found" error rather than a
# confusing wrapping failure.
p = make.Platform(
sys_platform="win32",
machine="amd64",
in_devcontainer=False,
vcvarsall_path=None,
)
# Stub locate_vcvarsall to return None.
original = make.locate_vcvarsall
try:
make.locate_vcvarsall = lambda: None
cmd = ["cmake", "-S", "."]
assert p.windows_msvc_wrap(cmd) == cmd
finally:
make.locate_vcvarsall = original
def test_windows_with_vcvarsall_emits_sentinel(self, tmp_path):
fake_vcvars = tmp_path / "vcvarsall.bat"
fake_vcvars.write_text("rem fake", encoding="utf-8")
p = make.Platform(
sys_platform="win32",
machine="amd64",
in_devcontainer=False,
vcvarsall_path=fake_vcvars,
)
wrapped = p.windows_msvc_wrap(["buf", "generate", ".."])
assert len(wrapped) == 1
line = wrapped[0]
assert line.startswith(make._WIN_SHELL_MARKER)
# The shell line must `call` vcvarsall and then `&&` the inner cmd.
body = line[len(make._WIN_SHELL_MARKER) :]
assert body.startswith(f'call "{fake_vcvars}" x64')
assert " >nul && buf generate .." in body
def test_windows_quotes_paths_with_spaces(self, tmp_path):
fake_vcvars = tmp_path / "vcvarsall.bat"
fake_vcvars.write_text("rem fake", encoding="utf-8")
p = make.Platform(
sys_platform="win32",
machine="amd64",
in_devcontainer=False,
vcvarsall_path=fake_vcvars,
)
wrapped = p.windows_msvc_wrap(["cmake", "-DPATH=C:\\Program Files\\foo"])
body = wrapped[0][len(make._WIN_SHELL_MARKER) :]
# The arg with a space MUST be quoted, but the bare cmake should not.
assert (
' cmake "-DPATH=C:\\Program Files\\foo"' in body
or ' cmake -DPATH="C:\\Program Files\\foo"' in body
or ' cmake "-DPATH=C:\\Program Files\\foo"' in body
or '"-DPATH=C:\\Program Files\\foo"' in body
) # at least one of these forms
# ---------------------------------------------------------------------------
# Unit: _winquote
# ---------------------------------------------------------------------------
class TestQuoting:
def test_empty_string(self):
assert make._winquote("") == '""'
def test_simple_arg_unchanged(self):
assert make._winquote("foo") == "foo"
assert make._winquote("--flag=value") == "--flag=value"
def test_arg_with_space_is_quoted(self):
assert make._winquote("hello world") == '"hello world"'
def test_arg_with_paren_is_quoted(self):
# The (x86) parser footgun from xxx.bat — must be quoted.
assert make._winquote("C:\\Program Files (x86)\\foo").startswith('"')
def test_arg_with_embedded_quote_is_doubled(self):
# cmd quotes embedded " by doubling.
assert make._winquote('say "hi"') == '"say ""hi"""'
# ---------------------------------------------------------------------------
# Unit: Runner
# ---------------------------------------------------------------------------
class TestRunner:
def test_dry_run_does_not_execute(self, capsys, tmp_path):
runner = make.Runner(verbose=False, dry_run=True)
# If this were actually executed, it would create a file we can detect.
marker = tmp_path / "should_not_exist.txt"
if sys.platform == "win32":
cmd = ["cmd", "/c", f"echo hi > {marker}"]
else:
cmd = ["sh", "-c", f"echo hi > {marker}"]
rc = runner.run(cmd)
assert rc == 0
assert not marker.exists(), "dry-run should not have executed"
out = capsys.readouterr().out
assert "[dry-run]" in out
def test_dry_run_prints_cwd(self, capsys, tmp_path):
runner = make.Runner(verbose=False, dry_run=True)
runner.run(["echo", "hi"], cwd=tmp_path)
out = capsys.readouterr().out
assert f"cwd={tmp_path}" in out
def test_sentinel_routes_through_shell(self, capsys):
runner = make.Runner(verbose=False, dry_run=True)
sentinel_cmd = [make._WIN_SHELL_MARKER + "echo hello-world"]
rc = runner.run(sentinel_cmd)
assert rc == 0
out = capsys.readouterr().out
# The marker must be stripped from the printed line.
assert make._WIN_SHELL_MARKER not in out
assert "echo hello-world" in out
def test_rmtree_dry_run_does_not_remove(self, capsys, tmp_path):
target = tmp_path / "doomed"
target.mkdir()
(target / "file.txt").write_text("x")
runner = make.Runner(verbose=False, dry_run=True)
runner.rmtree(target)
assert target.exists()
out = capsys.readouterr().out
assert "[dry-run] rm -rf" in out
def test_rmtree_real_removes(self, tmp_path):
target = tmp_path / "doomed"
target.mkdir()
(target / "file.txt").write_text("x")
runner = make.Runner(verbose=False, dry_run=False)
runner.rmtree(target)
assert not target.exists()
def test_rmtree_no_op_on_missing(self, tmp_path):
runner = make.Runner(verbose=False, dry_run=False)
runner.rmtree(tmp_path / "does-not-exist") # should not raise
def test_check_raises_on_failure(self):
runner = make.Runner(verbose=False, dry_run=False)
# `python -c "raise SystemExit(7)"` will exit 7.
with pytest.raises(SystemExit):
runner.run([sys.executable, "-c", "raise SystemExit(7)"])
def test_check_false_suppresses_failure(self):
runner = make.Runner(verbose=False, dry_run=False)
rc = runner.run([sys.executable, "-c", "raise SystemExit(7)"], check=False)
assert rc == 7
# ---------------------------------------------------------------------------
# Unit: vcpkg protobuf pin (baseline vs. overrides)
# ---------------------------------------------------------------------------
class TestVcpkgProtobufPin:
"""_resolve_vcpkg_protobuf_pin: baseline vs. overrides selection.
The git-history search (_resolve_vcpkg_baseline_for_protobuf) is stubbed
so these stay hermetic — we only assert the floor-based routing.
"""
def _patch_resolver(self, monkeypatch):
calls = []
def fake_resolve(version, vcpkg_root, runner):
calls.append(version)
return f"sha-for-{version}"
monkeypatch.setattr(
make, "_resolve_vcpkg_baseline_for_protobuf", fake_resolve
)
return calls
def test_at_or_above_floor_pins_exact_baseline(self, monkeypatch):
calls = self._patch_resolver(monkeypatch)
runner = make.Runner(verbose=False, dry_run=True)
pin = make._resolve_vcpkg_protobuf_pin("3.21.12", Path("/vcpkg"), runner)
assert pin.baseline == "sha-for-3.21.12"
assert pin.override_version is None # no overrides needed
assert calls == ["3.21.12"]
def test_floor_itself_has_no_override(self, monkeypatch):
self._patch_resolver(monkeypatch)
runner = make.Runner(verbose=False, dry_run=True)
pin = make._resolve_vcpkg_protobuf_pin("3.14.0", Path("/vcpkg"), runner)
assert pin.baseline == "sha-for-3.14.0"
assert pin.override_version is None
def test_below_floor_pins_floor_baseline_plus_override(self, monkeypatch):
calls = self._patch_resolver(monkeypatch)
runner = make.Runner(verbose=False, dry_run=True)
pin = make._resolve_vcpkg_protobuf_pin("3.12.0", Path("/vcpkg"), runner)
# builtin-baseline resolves the FLOOR, not the requested version.
assert pin.baseline == "sha-for-3.14.0"
assert pin.override_version == "3.12.0"
assert calls == ["3.14.0"]
def test_floor_str_matches_tuple(self):
assert make._VCPKG_PROTOBUF_BASELINE_FLOOR_STR == "3.14.0"
assert (
make._parse_protobuf_version_tuple(
make._VCPKG_PROTOBUF_BASELINE_FLOOR_STR
)
== make._VCPKG_PROTOBUF_BASELINE_FLOOR
)
# ----- below-floor existence validation (fail fast) -----
def test_below_floor_missing_raises_before_baseline_resolve(self, monkeypatch):
# A below-floor version absent from the registry must raise *before*
# any baseline git-search happens (so callers fail fast, trees intact).
baseline_calls = self._patch_resolver(monkeypatch)
monkeypatch.setattr(
make, "_protobuf_version_in_registry", lambda root, v: False
)
runner = make.Runner(verbose=False, dry_run=False)
with pytest.raises(RuntimeError) as exc:
make._resolve_vcpkg_protobuf_pin("3.12.99", Path("/vcpkg"), runner)
# Never reached the baseline resolver.
assert baseline_calls == []
assert "3.12.99" in str(exc.value)
assert "not present" in str(exc.value)
def test_below_floor_present_resolves(self, monkeypatch):
self._patch_resolver(monkeypatch)
monkeypatch.setattr(
make, "_protobuf_version_in_registry", lambda root, v: True
)
runner = make.Runner(verbose=False, dry_run=False)
pin = make._resolve_vcpkg_protobuf_pin("3.12.0", Path("/vcpkg"), runner)
assert pin.baseline == "sha-for-3.14.0"
assert pin.override_version == "3.12.0"
def test_below_floor_dry_run_skips_existence_check(self, monkeypatch):
# In dry-run there is no real checkout, so the registry must NOT be
# consulted — the pin should resolve via the placeholder path.
self._patch_resolver(monkeypatch)
def boom(root, v): # pragma: no cover - must never be called
raise AssertionError("registry consulted in dry-run")
monkeypatch.setattr(make, "_protobuf_version_in_registry", boom)
runner = make.Runner(verbose=False, dry_run=True)
pin = make._resolve_vcpkg_protobuf_pin("3.12.99", Path("/vcpkg"), runner)
assert pin.override_version == "3.12.99"
def test_resolve_below_floor_override_returns_none_above_floor(self, monkeypatch):
runner = make.Runner(verbose=False, dry_run=False)
assert (
make._resolve_below_floor_override("3.21.12", Path("/vcpkg"), runner)
is None
)
# ---------------------------------------------------------------------------
# Unit: protobuf hard support floor (3.8.0) + --force
# ---------------------------------------------------------------------------
class TestProtobufMinSupported:
"""_check_protobuf_min_supported: refuse < 3.8.0 unless forced."""
def test_below_floor_raises_without_force(self):
with pytest.raises(RuntimeError) as exc:
make._check_protobuf_min_supported("3.5.0", force=False)
msg = str(exc.value)
assert "3.5.0" in msg
assert make._PROTOBUF_MIN_SUPPORTED_STR in msg # "3.8.0"
assert "--force" in msg
def test_below_floor_with_force_warns_and_returns(self, capsys):
# Forced: must NOT raise; emits a warning to stderr instead.
make._check_protobuf_min_supported("3.5.0", force=True)
err = capsys.readouterr().err
assert "3.5.0" in err
assert "force" in err.lower()
def test_at_floor_is_allowed(self):
# 3.8.0 itself is supported (boundary inclusive) — no raise, no warning.
make._check_protobuf_min_supported("3.8.0", force=False)
def test_above_floor_is_allowed(self):
make._check_protobuf_min_supported("3.21.12", force=False)
def test_unparseable_version_is_allowed(self):
# Defensive: a non-numeric version is left for downstream resolution
# rather than rejected by the numeric floor guard.
make._check_protobuf_min_supported("main", force=False)
def test_floor_str_matches_tuple(self):
assert make._PROTOBUF_MIN_SUPPORTED_STR == "3.8.0"
assert (
make._parse_protobuf_version_tuple(make._PROTOBUF_MIN_SUPPORTED_STR)
== make._PROTOBUF_MIN_SUPPORTED
)
def test_support_floor_not_above_baseline_floor(self):
# The support floor must sit at/below the baseline floor so the
# overrides range it gates [support, baseline) is non-empty.
assert make._PROTOBUF_MIN_SUPPORTED <= make._VCPKG_PROTOBUF_BASELINE_FLOOR
class TestKnownVersionsHintFloor:
"""_format_known_protobuf_versions_hint: below-floor listing reaches 3.8.0.
The vcpkg version registry read is stubbed so the test is hermetic and
asserts only the floor-filtering / no-truncation behavior.
"""
# Newest-first registry, spanning above and below both floors plus a couple
# of pre-3.8.0 entries that must be dropped.
_REGISTRY = [
"6.33.4", "5.29.5", "4.25.1", "3.21.12", "3.18.0", "3.15.8",
"3.14.0", "3.13.0", "3.11.0", "3.9.0", "3.8.0", "3.7.0", "3.5.0",
]
def _patch_registry(self, monkeypatch):
monkeypatch.setattr(
make,
"_read_protobuf_registry_versions",
lambda root: list(self._REGISTRY),
)
def _listing_line(self, hint):
# The single line that enumerates the versions (starts with the
# "known protobuf versions" bullet), isolated from header notes that
# also mention the floor strings.
for line in hint.splitlines():
if "known protobuf versions" in line:
return line.split("): ", 1)[1]
raise AssertionError("no version-listing line in hint")
def test_include_below_floor_lists_down_to_support_floor(self, monkeypatch):
self._patch_registry(monkeypatch)
hint = make._format_known_protobuf_versions_hint(
Path("/vcpkg"), include_below_floor=True
)
listed = self._listing_line(hint)
# Reaches the support floor...
assert "3.8.0" in listed
# ...but excludes anything below it.
assert "3.7.0" not in listed
assert "3.5.0" not in listed
# No truncation marker — the full in-range list is shown.
assert "older)" not in hint
# Below-baseline versions (>= 3.8, < 3.14) are present.
assert "3.9.0" in listed and "3.11.0" in listed
def test_baseline_only_listing_still_filters_to_baseline_floor(
self, monkeypatch
):
self._patch_registry(monkeypatch)
hint = make._format_known_protobuf_versions_hint(
Path("/vcpkg"), include_below_floor=False
)
listed = self._listing_line(hint)
# Default listing only surfaces >= 3.14.0 (usable as builtin-baseline).
assert "3.14.0" in listed
assert "3.13.0" not in listed
assert "3.8.0" not in listed
# ---------------------------------------------------------------------------
# Unit: repo root discovery
# ---------------------------------------------------------------------------
class TestRepoRoot:
def test_finds_root_from_repo(self):
assert make.find_repo_root() == REPO_ROOT
def test_finds_root_from_subdir(self):
# Walk into a deep subdir and ensure we still locate it.
deep = REPO_ROOT / "internal" / "options"
if deep.is_dir():
assert make.find_repo_root(deep) == REPO_ROOT
def test_raises_outside_repo(self, tmp_path):
with pytest.raises(SystemExit):
make.find_repo_root(tmp_path)
# ---------------------------------------------------------------------------
# Unit: lang directory mapping
# ---------------------------------------------------------------------------
class TestLangDir:
def test_go(self):
assert (
make._lang_dir(REPO_ROOT, "go") == REPO_ROOT / "test" / "go-tableau-loader"
)
def test_cpp(self):
assert (
make._lang_dir(REPO_ROOT, "cpp")
== REPO_ROOT / "test" / "cpp-tableau-loader"
)
def test_csharp(self):
assert (
make._lang_dir(REPO_ROOT, "csharp")
== REPO_ROOT / "test" / "csharp-tableau-loader"
)
# ---------------------------------------------------------------------------
# Subprocess helpers
# ---------------------------------------------------------------------------
def run_make(*args: str, cwd: Path = REPO_ROOT) -> subprocess.CompletedProcess:
"""Spawn `python3 make.py <args...>` and capture stdout+stderr."""
return subprocess.run(
[sys.executable, str(MAKE_PY), *args],
cwd=str(cwd),
capture_output=True,
text=True,
check=False,
)
# ---------------------------------------------------------------------------
# Integration: top-level invocations
# ---------------------------------------------------------------------------
class TestTopLevel:
def test_help_exits_zero(self):
proc = run_make("--help")
assert proc.returncode == 0
assert "make.py" in proc.stdout
assert "setup" in proc.stdout
assert "test" in proc.stdout
def test_no_args_prints_help(self):
proc = run_make()
assert proc.returncode == 0
assert "usage:" in proc.stdout.lower()
def test_version_prints_versions_env(self):
proc = run_make("--version")
assert proc.returncode == 0
assert f"make.py {make.MAKE_PY_VERSION}" in proc.stdout
# Must echo every key from versions.env.
for key in (
"GO_VERSION",
"BUF_VERSION",
"DEFAULT_VARIANT",
"MODERN_PROTOBUF_VERSION",
"MODERN_VCPKG_BASELINE_COMMIT",
"LEGACY_V3_PROTOBUF_VERSION",
"LEGACY_V3_VCPKG_BASELINE_COMMIT",
"DOTNET_VERSION",
"CMAKE_VERSION",
):
assert key in proc.stdout, f"--version missing {key}"
def test_env_emits_valid_json(self):
proc = run_make("env")
assert proc.returncode == 0
info = json.loads(proc.stdout)
# Sanity-check structure.
assert info["make_py_version"] == make.MAKE_PY_VERSION
assert "sys_platform" in info
assert "vcpkg_triplet" in info
assert "tools" in info
assert "versions_env" in info
assert info["versions_env"]["GO_VERSION"]
# ---------------------------------------------------------------------------
# Integration: dry-run snapshots
# ---------------------------------------------------------------------------
class TestDryRunGo:
def test_test_lang_go(self):
proc = run_make("--dry-run", "test", "--lang", "go")
assert proc.returncode == 0
out = proc.stdout
assert "buf generate .." in out
assert "go test" in out
assert "-timeout" in out and "30m" in out
# -race default depends on host OS; covered separately in
# test_test_lang_go_race_default_matches_host.
def test_test_lang_go_no_race(self):
proc = run_make("--dry-run", "test", "--lang", "go", "--no-race")
assert proc.returncode == 0
# When --no-race is passed, "-race" must NOT appear in the go test line.
for line in proc.stdout.splitlines():
if "go test" in line:
assert "-race" not in line, f"Expected --no-race to drop -race: {line}"
def test_test_lang_go_race_default_matches_host(self):
# Default --race depends on host OS:
# - Windows -> default OFF (-race needs cgo + C compiler)
# - Linux/macOS -> default ON
proc = run_make("--dry-run", "test", "--lang", "go")
assert proc.returncode == 0
go_test_lines = [l for l in proc.stdout.splitlines() if "go test" in l]
assert go_test_lines, "no go test line"
joined = "\n".join(go_test_lines)
if sys.platform == "win32":
assert "-race" not in joined, "Windows default should NOT include -race"
else:
assert "-race" in joined, "Linux/macOS default should include -race"
def test_test_lang_go_explicit_race_forces_on(self):
# Even on Windows, --race explicitly enables it (user opt-in).
proc = run_make("--dry-run", "test", "--lang", "go", "--race")
assert proc.returncode == 0
go_test_lines = [l for l in proc.stdout.splitlines() if "go test" in l]
joined = "\n".join(go_test_lines)
assert "-race" in joined, "--race must force -race on regardless of host"
def test_test_lang_go_smoke_skips_buf_generate(self):
proc = run_make("--dry-run", "test", "--lang", "go", "--smoke")
assert proc.returncode == 0
# Smoke must NOT call buf generate; only go vet on the plugin packages.
assert "buf generate" not in proc.stdout
assert "go vet" in proc.stdout
# Specific plugin packages required.
for pkg in (
"./cmd/...",
"./pkg/...",
"./internal/options/...",
"./internal/loadutil/...",
"./internal/xproto/...",
):
assert pkg in proc.stdout, f"smoke missing {pkg}"
def test_test_lang_go_filter(self):
proc = run_make(
"--dry-run", "test", "--lang", "go", "-k", "Test_ActivityConf_OrderedMap"
)
assert proc.returncode == 0
assert "-run" in proc.stdout
assert "Test_ActivityConf_OrderedMap" in proc.stdout
def test_test_lang_go_coverage(self):
proc = run_make("--dry-run", "test", "--lang", "go", "--coverage")
assert proc.returncode == 0
assert "-coverprofile=coverage.txt" in proc.stdout
assert "-covermode=atomic" in proc.stdout
class TestDryRunCpp:
def test_test_lang_cpp_default(self):
proc = run_make("--dry-run", "test", "--lang", "cpp")
assert proc.returncode == 0
out = proc.stdout
assert "buf generate .." in out
assert "cmake -S . -B build" in out
assert "-DCMAKE_BUILD_TYPE=Debug" in out
assert "-DCMAKE_CXX_STANDARD=17" in out
assert "cmake --build build --parallel" in out
assert "ctest --test-dir build --output-on-failure" in out
def test_test_lang_cpp_no_clean_skips_wipe(self):
proc_clean = run_make("--dry-run", "test", "--lang", "cpp")
proc_no_clean = run_make("--dry-run", "test", "--lang", "cpp", "--no-clean")
# Clean run must mention rm-rf the build/src dirs; --no-clean must not.
assert "rm -rf" in proc_clean.stdout
assert "build" in proc_clean.stdout
assert "rm -rf" not in proc_no_clean.stdout
def test_test_lang_cpp_cxx_std_20(self):
proc = run_make("--dry-run", "test", "--lang", "cpp", "--cxx-std", "20")
assert proc.returncode == 0
assert "-DCMAKE_CXX_STANDARD=20" in proc.stdout
assert "-DCMAKE_CXX_STANDARD=17" not in proc.stdout
def test_test_lang_cpp_cxx_compiler_clang(self):
proc = run_make("--dry-run", "test", "--lang", "cpp", "--cxx-compiler", "clang")
assert proc.returncode == 0
assert "-DCMAKE_CXX_COMPILER=clang++" in proc.stdout
def test_test_lang_cpp_protobuf_version_manifest_mode(self):
proc = run_make(
"--dry-run",
"test",
"--lang",
"cpp",
"--protobuf-version",
"3.21.12",
"--triplet",
"x64-windows-static",
"--no-clean",
)
assert proc.returncode == 0
out = proc.stdout
# Manifest-mode flags MUST appear when --protobuf-version is set.
assert "-DVCPKG_INSTALLED_DIR=" in out
assert "-DVCPKG_MANIFEST_INSTALL=OFF" in out
# Must also `vcpkg install` the manifest before cmake configure.
assert "vcpkg" in out and "install" in out
# Triplet must be plumbed through.
assert "--triplet=x64-windows-static" in out
def test_test_lang_cpp_manifest_no_vcpkg_root_dry_run_ok(self, monkeypatch):
# On a host with no VCPKG_ROOT (e.g. CI runner of testing-make.yml),
# --dry-run must still print the command sequence rather than abort.
# Real (non-dry-run) execution still hard-errors via a separate code
# path; that's covered by the unit test in TestPlatform.
monkeypatch.delenv("VCPKG_ROOT", raising=False)
proc = run_make(
"--dry-run",
"test",
"--lang",
"cpp",
"--protobuf-version",
"3.21.12",
"--triplet",
"x64-linux",
"--no-clean",
)
assert proc.returncode == 0, proc.stderr
assert "-DVCPKG_INSTALLED_DIR=" in proc.stdout
assert "-DVCPKG_MANIFEST_INSTALL=OFF" in proc.stdout
def test_test_lang_cpp_manifest_forces_toolchain_on_linux(self, monkeypatch):
# Manifest mode must emit -DCMAKE_TOOLCHAIN_FILE even on Linux:
# find_package(Protobuf) needs vcpkg's vcpkg.cmake to resolve the
# manifest-installed protobuf. Plain Linux (no --protobuf-version)
# would correctly get [] (system protobuf via apt).
monkeypatch.setenv("VCPKG_ROOT", "/tmp/fake-vcpkg")
proc = run_make(
"--dry-run",
"test",
"--lang",
"cpp",
"--protobuf-version",
"3.21.12",
"--triplet",
"x64-linux",
"--no-clean",
)
assert proc.returncode == 0, proc.stderr
# Must have toolchain flags for the manifest install to be picked up.
assert "-DCMAKE_TOOLCHAIN_FILE=" in proc.stdout
assert "-DVCPKG_TARGET_TRIPLET=x64-linux" in proc.stdout
def test_test_lang_cpp_no_vcpkg_install_skips_install(self):
proc = run_make(
"--dry-run",
"test",
"--lang",
"cpp",
"--protobuf-version",
"3.21.12",
"--triplet",
"x64-windows-static",
"--no-clean",
"--no-vcpkg-install",
)
assert proc.returncode == 0
# No `vcpkg ... install ...` line when --no-vcpkg-install is set.
# cmake configure still runs, with the manifest-mode flags.
assert "-DVCPKG_INSTALLED_DIR=" in proc.stdout
for line in proc.stdout.splitlines():
# `vcpkg install` must not appear; `cmake` calls are fine.
if "vcpkg.exe install" in line or "vcpkg install" in line.replace(
".exe", ""
):
pytest.fail(f"--no-vcpkg-install did not skip vcpkg install: {line}")
def test_test_lang_cpp_filter(self):
proc = run_make(
"--dry-run", "test", "--lang", "cpp", "-k", "HubTest.Load", "--no-clean"
)
assert proc.returncode == 0
# ctest -R <pattern>
ctest_lines = [l for l in proc.stdout.splitlines() if "ctest" in l]
assert ctest_lines, "no ctest line in output"
joined = "\n".join(ctest_lines)
assert "-R" in joined and "HubTest.Load" in joined
class TestDryRunCsharp:
def test_test_lang_csharp_default(self):
proc = run_make("--dry-run", "test", "--lang", "csharp")
assert proc.returncode == 0
assert "buf generate .." in proc.stdout
assert "dotnet test" in proc.stdout
assert "--nologo" in proc.stdout
def test_test_lang_csharp_filter(self):
proc = run_make("--dry-run", "test", "--lang", "csharp", "-k", "HubTest.Load")
assert proc.returncode == 0
# dotnet test --filter "FullyQualifiedName~<x>"
assert "FullyQualifiedName~HubTest.Load" in proc.stdout
class TestDryRunGenerateAndBuild:
def test_generate_lang_go(self):
proc = run_make("--dry-run", "generate", "--lang", "go")
assert proc.returncode == 0
assert "buf generate .." in proc.stdout
def test_generate_lang_cpp(self):