-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathtest_packagesettings.py
More file actions
934 lines (811 loc) · 29.6 KB
/
Copy pathtest_packagesettings.py
File metadata and controls
934 lines (811 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
import pathlib
import typing
from unittest.mock import Mock, patch
import pydantic
import pytest
from packaging.requirements import Requirement
from packaging.utils import NormalizedName
from packaging.version import Version
from fromager import build_environment, context
from fromager.packagesettings import (
Annotations,
BuildDirectory,
EnvVars,
GitOptions,
Package,
PackageBuildInfo,
PackageSettings,
ResolverDist,
Settings,
SettingsFile,
Variant,
substitute_template,
)
from fromager.packagesettings._typedefs import PurlType, UpstreamPurl
TEST_PKG = "test-pkg"
TEST_EMPTY_PKG = "test-empty-pkg"
TEST_OTHER_PKG = "test-other-pkg"
TEST_RELATED_PKG = "test-pkg-library"
TEST_PREBUILT_PKG = "test-prebuilt-pkg"
TEST_COOLDOWN_PKG = "test-cooldown-pkg"
FULL_EXPECTED: dict[str, typing.Any] = {
"annotations": {
"fromager.test.value": "somevalue",
"fromager.test.override": "variant override",
},
"build_dir": pathlib.Path("python"),
"build_options": {
"build_ext_parallel": True,
"cpu_cores_per_job": 4,
"memory_per_job_gb": 4.0,
"exclusive_build": False,
},
"changelog": {
Version("1.0.1"): ["fixed bug"],
Version("1.0.2"): ["more bugs", "rebuild"],
},
"config_settings": {
"setup-args": [
"-Dsystem-freetype=true",
"-Dsystem-qhull=true",
],
"cmake.define.BLA_VENDOR": "OpenBLAS",
},
"download_source": {
"destination_filename": "${canonicalized_name}-${version}.tar.gz",
"url": "https://egg.test/${canonicalized_name}/v${version}.tar.gz",
},
"env": {
"EGG": "spam",
"EGG_AGAIN": "$EGG",
"SPAM": "alot $EXTRA",
"QUOTES": "A\"BC'$$EGG",
"DEF": "${DEF:-default}",
"EXTRA_MAX_JOBS": "${MAX_JOBS}",
"MY_VERSION": "${__version__}",
},
"git_options": {
"submodules": False,
"submodule_paths": [],
},
"name": "test-pkg",
"has_config": True,
"purl": None,
"project_override": {
"remove_build_requires": ["cmake"],
"update_build_requires": ["setuptools>=68.0.0", "torch"],
"requires_external": ["openssl-libs"],
},
"resolver_dist": {
"include_sdists": True,
"include_wheels": True,
"sdist_server_url": "https://sdist.test/egg",
"ignore_platform": True,
"use_pypi_org_metadata": True,
"min_release_age": None,
},
"variants": {
"cpu": {
"annotations": {
"fromager.test.override": "cpu override",
},
"env": {"EGG": "spam ${EGG}", "EGG_AGAIN": "$EGG"},
"wheel_server_url": "https://wheel.test/simple",
"pre_built": False,
},
"rocm": {
"annotations": {
"fromager.test.override": "amd override",
},
"env": {"SPAM": ""},
"wheel_server_url": None,
"pre_built": True,
},
"cuda": {
"annotations": None,
"env": {},
"wheel_server_url": None,
"pre_built": False,
},
},
}
EMPTY_EXPECTED: dict[str, typing.Any] = {
"name": "test-empty-pkg",
"annotations": None,
"build_dir": None,
"build_options": {
"build_ext_parallel": False,
"cpu_cores_per_job": 1,
"memory_per_job_gb": 1.0,
"exclusive_build": False,
},
"changelog": {},
"config_settings": {},
"env": {},
"download_source": {
"url": None,
"destination_filename": None,
},
"git_options": {
"submodules": False,
"submodule_paths": [],
},
"has_config": True,
"purl": None,
"project_override": {
"remove_build_requires": [],
"update_build_requires": [],
"requires_external": [],
},
"resolver_dist": {
"sdist_server_url": None,
"include_sdists": True,
"include_wheels": False,
"ignore_platform": False,
"use_pypi_org_metadata": None,
"min_release_age": None,
},
"variants": {},
}
PREBUILT_PKG_EXPECTED: dict[str, typing.Any] = {
"name": "test-prebuilt-pkg",
"annotations": None,
"build_dir": None,
"build_options": {
"build_ext_parallel": False,
"cpu_cores_per_job": 1,
"memory_per_job_gb": 1.0,
"exclusive_build": False,
},
"changelog": {
Version("1.0.1"): ["onboard"],
},
"config_settings": {},
"env": {},
"download_source": {
"url": None,
"destination_filename": None,
},
"git_options": {
"submodules": False,
"submodule_paths": [],
},
"has_config": True,
"purl": None,
"project_override": {
"remove_build_requires": [],
"update_build_requires": [],
"requires_external": [],
},
"resolver_dist": {
"sdist_server_url": None,
"include_sdists": True,
"include_wheels": False,
"ignore_platform": False,
"use_pypi_org_metadata": None,
"min_release_age": None,
},
"variants": {
"cpu": {
"annotations": None,
"env": {},
"pre_built": True,
"wheel_server_url": None,
},
},
}
def test_parse_full(testdata_path: pathlib.Path) -> None:
filename = testdata_path / "context/overrides/settings/test_pkg.yaml"
p = PackageSettings.from_string(TEST_PKG, filename.read_text())
assert p.model_dump() == FULL_EXPECTED
def test_parse_full_file(testdata_path: pathlib.Path) -> None:
filename = testdata_path / "context/overrides/settings/test_pkg.yaml"
p = PackageSettings.from_file(filename)
assert p.model_dump() == FULL_EXPECTED
def test_parse_minimal(testdata_path: pathlib.Path) -> None:
filename = testdata_path / "context/overrides/settings/test_empty_pkg.yaml"
p = PackageSettings.from_string(TEST_EMPTY_PKG, filename.read_text())
assert p.model_dump() == EMPTY_EXPECTED
def test_parse_minimal_file(testdata_path: pathlib.Path) -> None:
filename = testdata_path / "context/overrides/settings/test_empty_pkg.yaml"
p = PackageSettings.from_file(filename)
assert p.model_dump() == EMPTY_EXPECTED
def test_parse_prebuilt_file(testdata_path: pathlib.Path) -> None:
filename = testdata_path / "context/overrides/settings/test_prebuilt_pkg.yaml"
p = PackageSettings.from_file(filename)
assert p.model_dump() == PREBUILT_PKG_EXPECTED
def test_default_settings() -> None:
p = PackageSettings.from_default(TEST_EMPTY_PKG)
expected = EMPTY_EXPECTED.copy()
expected["has_config"] = False
assert p.model_dump() == expected
def test_pbi_test_pkg_extra_environ(
tmp_path: pathlib.Path, testdata_context: context.WorkContext
) -> None:
testdata_context.settings.max_jobs = 1
parallel = {
"CMAKE_BUILD_PARALLEL_LEVEL": "1",
"MAKEFLAGS": "-j1",
"MAX_JOBS": "1",
"EXTRA_MAX_JOBS": "1",
}
version = Version("1.0.0")
version_env = {
"MY_VERSION": "1.0.0",
}
pbi = testdata_context.settings.package_build_info(TEST_PKG)
result = pbi.get_extra_environ(template_env={"EXTRA": "extra"}, version=version)
assert (
result
== {
"EGG": "spam spam",
"EGG_AGAIN": "spam spam",
"QUOTES": "A\"BC'$EGG", # $$EGG is transformed into $EGG
"SPAM": "alot extra",
"DEF": "default",
}
| version_env
| parallel
)
assert "__version__" not in result
result = pbi.get_extra_environ(
template_env={"EXTRA": "extra", "DEF": "nondefault"}, version=version
)
assert (
result
== {
"EGG": "spam spam",
"EGG_AGAIN": "spam spam",
"QUOTES": "A\"BC'$EGG", # $$EGG is transformed into $EGG
"SPAM": "alot extra",
"DEF": "nondefault",
}
| version_env
| parallel
)
assert "__version__" not in result
testdata_context.settings.variant = Variant("rocm")
pbi = testdata_context.settings.package_build_info(TEST_PKG)
result = pbi.get_extra_environ(template_env={"EXTRA": "extra"}, version=version)
assert (
result
== {
"EGG": "spam",
"EGG_AGAIN": "spam",
"QUOTES": "A\"BC'$EGG",
"SPAM": "",
"DEF": "default",
}
| version_env
| parallel
)
assert "__version__" not in result
testdata_context.settings.variant = Variant("cuda")
pbi = testdata_context.settings.package_build_info(TEST_PKG)
result = pbi.get_extra_environ(template_env={"EXTRA": "spam"}, version=version)
assert (
result
== {
"EGG": "spam",
"EGG_AGAIN": "spam",
"QUOTES": "A\"BC'$EGG",
"SPAM": "alot spam",
"DEF": "default",
}
| version_env
| parallel
)
assert "__version__" not in result
build_env = build_environment.BuildEnvironment(
testdata_context,
parent_dir=tmp_path,
)
result = pbi.get_extra_environ(
template_env={"EXTRA": "spam", "PATH": "/sbin:/bin"},
build_env=build_env,
version=version,
)
assert (
result
== {
"EGG": "spam",
"EGG_AGAIN": "spam",
"QUOTES": "A\"BC'$EGG",
"SPAM": "alot spam",
"DEF": "default",
"PATH": f"{build_env.path / 'bin'}:/sbin:/bin",
"VIRTUAL_ENV": str(build_env.path),
"UV_CACHE_DIR": str(testdata_context.uv_cache),
"UV_NATIVE_TLS": "true",
"UV_NO_MANAGED_PYTHON": "true",
"UV_PYTHON": str(build_env.python),
"UV_PYTHON_DOWNLOADS": "never",
}
| version_env
| parallel
)
assert "__version__" not in result
def test_pbi_test_pkg(testdata_context: context.WorkContext) -> None:
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.package == NormalizedName(TEST_PKG)
assert pbi.variant == Variant(testdata_context.settings.variant)
assert pbi.pre_built is False
assert pbi.has_config is True
assert pbi.wheel_server_url == "https://wheel.test/simple"
assert pbi.override_module_name == "test_pkg"
assert (
pbi.download_source_url(Version("1.0.2"), resolve_template=False)
== "https://egg.test/${canonicalized_name}/v${version}.tar.gz"
)
assert (
pbi.download_source_url(Version("1.0.2"))
== "https://egg.test/test-pkg/v1.0.2.tar.gz"
)
assert (
pbi.download_source_destination_filename(
Version("1.0.2"), resolve_template=False
)
== "${canonicalized_name}-${version}.tar.gz"
)
assert (
pbi.download_source_destination_filename(Version("1.0.2"))
== "test-pkg-1.0.2.tar.gz"
)
assert pbi.resolver_include_sdists is True
assert pbi.resolver_include_wheels is True
assert pbi.resolver_ignore_platform is True
assert (
pbi.resolver_sdist_server_url("https://pypi.org/simple")
== "https://sdist.test/egg"
)
assert pbi.build_tag(Version("1.0.2")) == (2, "")
sdist_root_dir = pathlib.Path("/sdist-root")
assert pbi.build_dir(sdist_root_dir) == sdist_root_dir / "python"
def test_pbi_test_pkg_patches(testdata_context: context.WorkContext) -> None:
pbi = testdata_context.settings.package_build_info(TEST_PKG)
norm_test_pkg = TEST_PKG.replace("-", "_")
unversioned_patchdir = testdata_context.settings.patches_dir / norm_test_pkg
versioned_patchdir = (
testdata_context.settings.patches_dir / f"{norm_test_pkg}-1.0.2"
)
patch001 = versioned_patchdir / "001-somepatch.patch"
patch002 = versioned_patchdir / "002-otherpatch.patch"
patch004 = unversioned_patchdir / "cpu" / "004-cpu.patch"
patch005 = versioned_patchdir / "cpu" / "005-cpuver.patch"
patch010 = unversioned_patchdir / "010-unversioned.patch"
assert pbi.get_all_patches() == {
None: [patch004, patch010],
Version("1.0.2"): [patch001, patch002, patch005],
}
assert pbi.get_all_patches() is pbi.get_all_patches()
assert pbi.get_patches(Version("1.0.2")) == [
patch001,
patch002,
patch004,
patch005,
patch010,
]
assert pbi.get_patches(Version("1.0.2+local")) == pbi.get_patches(Version("1.0.2"))
assert pbi.get_patches(Version("1.0.1")) == [
patch004,
patch010,
]
def test_pbi_other(testdata_context: context.WorkContext) -> None:
pbi = testdata_context.settings.package_build_info(TEST_OTHER_PKG)
assert pbi.package == NormalizedName(TEST_OTHER_PKG)
assert pbi.variant == Variant(testdata_context.settings.variant)
assert pbi.pre_built is False
assert pbi.has_config is False
assert pbi.wheel_server_url is None
assert pbi.override_module_name == "test_other_pkg"
assert pbi.download_source_url(Version("1.0.0")) is None
assert pbi.download_source_destination_filename(Version("1.0.0")) is None
assert pbi.download_source_destination_filename(Version("1.0.0")) is None
assert pbi.resolver_include_sdists is True
assert pbi.resolver_include_wheels is False
assert (
pbi.resolver_sdist_server_url("https://pypi.org/simple")
== "https://pypi.org/simple"
)
assert pbi.build_tag(Version("1.0.0")) == ()
sdist_root_dir = pathlib.Path("/sdist-root")
assert pbi.build_dir(sdist_root_dir) == sdist_root_dir
patchdir = (
testdata_context.settings.patches_dir
/ f"{TEST_OTHER_PKG.replace('-', '_')}-1.0.0"
)
assert pbi.get_all_patches() == {
Version("1.0.0"): [
patchdir / "001-mypatch.patch",
],
}
assert pbi.get_all_patches() is pbi.get_all_patches()
def test_type_envvars() -> None:
ta = pydantic.TypeAdapter(EnvVars)
v = ta.validate_python(
{"int": 1, "float": 2.0, "true": True, "false": False, "str": "string"}
)
assert v == {
"int": "1",
"float": "2.0",
"true": "1",
"false": "0",
"str": "string",
}
with pytest.raises(ValueError):
ta.validate_python({"shell": "$(subshell)"})
with pytest.raises(TypeError):
ta.validate_python({"none": None})
def test_type_package() -> None:
ta = pydantic.TypeAdapter(Package)
assert ta.validate_python("Some_Package") == "some-package"
assert ta.validate_python("some.package") == "some-package"
with pytest.raises(ValueError):
ta.validate_python("invalid/package")
def test_type_builddirectory() -> None:
ta = pydantic.TypeAdapter(BuildDirectory)
assert ta.validate_python("python") == pathlib.Path("python")
assert ta.validate_python("../tmp/build") == pathlib.Path("../tmp/build")
with pytest.raises(ValueError):
ta.validate_python("/absolute/path")
def test_type_purl_type() -> None:
"""Verify PurlType normalizes and rejects empty strings."""
ta = pydantic.TypeAdapter(PurlType)
assert ta.validate_python("pypi") == "pypi"
assert ta.validate_python(" Generic ") == "generic"
assert ta.validate_python("GITHUB") == "github"
with pytest.raises(ValueError):
ta.validate_python("")
with pytest.raises(ValueError):
ta.validate_python(" ")
def test_type_upstream_purl() -> None:
"""Verify UpstreamPurl accepts valid purls and rejects invalid strings."""
ta = pydantic.TypeAdapter(UpstreamPurl)
assert ta.validate_python("pkg:pypi/flask@2.0") == "pkg:pypi/flask@2.0"
assert (
ta.validate_python("pkg:github/vllm-project/bart-plugin@v0.2.0")
== "pkg:github/vllm-project/bart-plugin@v0.2.0"
)
with pytest.raises(ValueError):
ta.validate_python("invalid-not-purl")
with pytest.raises(ValueError):
ta.validate_python("")
def test_global_settings(testdata_path: pathlib.Path) -> None:
filename = testdata_path / "context/overrides/settings.yaml"
gs = SettingsFile.from_file(filename)
assert gs.changelog == {
"rocm": [
"setuptools upgraded to 82.0.0",
],
}
def test_settings_overrides(testdata_context: context.WorkContext) -> None:
assert testdata_context.settings.list_overrides() == {
TEST_PKG,
TEST_EMPTY_PKG,
TEST_OTHER_PKG,
TEST_RELATED_PKG,
TEST_PREBUILT_PKG,
TEST_COOLDOWN_PKG,
}
def test_global_changelog(testdata_context: context.WorkContext) -> None:
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.package == TEST_PKG
assert not pbi.pre_built
assert pbi.variant == "cpu"
assert pbi.build_tag(Version("0.99")) == ()
assert pbi.build_tag(Version("1.0.1")) == (1, "")
assert pbi.build_tag(Version("1.0.2")) == (2, "")
assert pbi.build_tag(Version("1.0.2+local")) == pbi.build_tag(Version("1.0.2"))
assert pbi.build_tag(Version("2.0.0")) == ()
# CUDA variant has no global changelog
testdata_context.settings.variant = Variant("cuda")
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.package == TEST_PKG
assert not pbi.pre_built
assert pbi.variant == "cuda"
assert pbi.build_tag(Version("0.99")) == ()
assert pbi.build_tag(Version("1.0.1")) == (1, "")
assert pbi.build_tag(Version("1.0.2")) == (2, "")
assert pbi.build_tag(Version("1.0.2+local")) == pbi.build_tag(Version("1.0.2"))
assert pbi.build_tag(Version("2.0.0")) == ()
# ROCm variant has pre-built flag
testdata_context.settings.variant = Variant("rocm")
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.package == TEST_PKG
assert pbi.pre_built
assert pbi.variant == "rocm"
assert pbi.build_tag(Version("0.99")) == ()
testdata_context.settings.variant = Variant("cpu")
pbi = testdata_context.settings.package_build_info(TEST_PREBUILT_PKG)
assert pbi.package == TEST_PREBUILT_PKG
assert pbi.pre_built
assert pbi.variant == "cpu"
assert pbi.get_changelog(Version("1.0.1")) == ["onboard"]
assert pbi.build_tag(Version("1.0.1")) == ()
def test_settings_list(testdata_context: context.WorkContext) -> None:
assert testdata_context.settings.list_overrides() == {
TEST_COOLDOWN_PKG,
TEST_EMPTY_PKG,
TEST_OTHER_PKG,
TEST_PKG,
TEST_RELATED_PKG,
TEST_PREBUILT_PKG,
}
assert testdata_context.settings.list_pre_built() == {TEST_PREBUILT_PKG}
assert testdata_context.settings.variant_changelog() == []
testdata_context.settings.variant = Variant("rocm")
assert testdata_context.settings.list_pre_built() == {TEST_PKG}
assert testdata_context.settings.variant_changelog() == [
"setuptools upgraded to 82.0.0"
]
@patch("fromager.packagesettings._pbi.get_cpu_count", return_value=8)
@patch("fromager.packagesettings._pbi.get_available_memory_gib", return_value=7.1)
def test_parallel_jobs(
get_available_memory_gib: Mock,
get_cpu_count: Mock,
testdata_context: context.WorkContext,
) -> None:
assert testdata_context.settings.max_jobs is None
pbi = testdata_context.settings.package_build_info(TEST_EMPTY_PKG)
assert pbi.parallel_jobs() == 7
get_cpu_count.return_value = 4
assert pbi.parallel_jobs() == 4
get_available_memory_gib.return_value = 2.1
assert pbi.parallel_jobs() == 2
get_available_memory_gib.return_value = 1.5
assert pbi.parallel_jobs() == 1
testdata_context.settings.max_jobs = 2
pbi = testdata_context.settings.package_build_info(TEST_EMPTY_PKG)
get_available_memory_gib.return_value = 23
assert pbi.parallel_jobs() == 2
# test-pkg needs more memory
testdata_context.settings.max_jobs = 200
pbi = testdata_context.settings.package_build_info(TEST_PKG)
get_cpu_count.return_value = 16
get_available_memory_gib.return_value = 20
assert pbi.parallel_jobs() == 4
get_cpu_count.return_value = 32
get_available_memory_gib.return_value = 25
assert pbi.parallel_jobs() == 6
testdata_context.settings.max_jobs = 4
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.parallel_jobs() == 4
@pytest.mark.parametrize(
"value,template_env,expected",
[
("", {}, ""),
("${var}", {"var": "value"}, "value"),
("$${var}", {"var": "value"}, "${var}"),
("${var:-}", {}, ""),
("${var:-default}", {}, "default"),
("${var:-default}", {"var": "value"}, "value"),
("$${var:-default}", {}, "${var:-default}"),
],
)
def test_substitute_template(
value: str, template_env: dict[str, str], expected: str
) -> None:
assert substitute_template(value, template_env) == expected
def test_substitute_template_key_error() -> None:
# This test expects a ValueError to be raised by substitute_template
with pytest.raises(ValueError) as excinfo:
substitute_template("${DEFAULT:-default} ${UNKNOWN}", {})
# Verify that the error message matches the expected message
assert (
str(excinfo.value)
== "Undefined environment variable KeyError('UNKNOWN') referenced in expression '${DEFAULT} ${UNKNOWN}'"
)
def test_git_options_default() -> None:
"""Test that GitOptions has correct default values."""
git_opts = GitOptions()
assert git_opts.submodules is False
assert git_opts.submodule_paths == []
def test_git_options_with_submodules_enabled() -> None:
"""Test GitOptions with submodules enabled."""
git_opts = GitOptions(submodules=True)
assert git_opts.submodules is True
assert git_opts.submodule_paths == []
def test_git_options_with_specific_paths() -> None:
"""Test GitOptions with specific submodule paths."""
paths = ["vendor/lib1", "vendor/lib2"]
git_opts = GitOptions(submodule_paths=paths)
assert git_opts.submodules is False # Default value
assert git_opts.submodule_paths == paths
def test_git_options_with_both_settings() -> None:
"""Test GitOptions with both submodules and paths configured."""
paths = ["vendor/lib1"]
git_opts = GitOptions(submodules=True, submodule_paths=paths)
assert git_opts.submodules is True
assert git_opts.submodule_paths == paths
def test_package_settings_git_options_default() -> None:
"""Test that PackageSettings includes GitOptions with defaults."""
settings = PackageSettings.from_default("test-pkg")
assert hasattr(settings, "git_options")
assert isinstance(settings.git_options, GitOptions)
assert settings.git_options.submodules is False
assert settings.git_options.submodule_paths == []
def test_package_settings_git_options_from_dict() -> None:
"""Test PackageSettings can parse git_options from dictionary."""
settings = PackageSettings.model_validate(
{
"name": "test-pkg",
"has_config": True,
"git_options": {
"submodules": True,
},
}
)
assert settings.git_options.submodules is True
assert settings.git_options.submodule_paths == [] # Default value
def test_package_settings_git_options_from_dict_empty() -> None:
"""Test PackageSettings can parse empty git_options from dictionary."""
settings = PackageSettings.model_validate(
{"name": "test-pkg", "has_config": True, "git_options": {}}
)
assert settings.git_options.submodules is False # Default value
assert settings.git_options.submodule_paths == [] # Default value
def test_package_settings_git_options_from_file() -> None:
"""Test PackageSettings can parse git_options from a YAML file."""
data = """
git_options:
submodules: true
submodule_paths:
- path/to/submodule
"""
settings = PackageSettings.from_string("test-pkg", data)
assert settings.git_options.submodules is True
assert settings.git_options.submodule_paths == ["path/to/submodule"]
def test_package_build_info_git_options(testdata_context: context.WorkContext) -> None:
"""Test that PackageBuildInfo exposes git_options property."""
req = Requirement("test-pkg==1.0.0")
pbi = testdata_context.package_build_info(req)
# Check that git_options property exists and returns GitOptions
assert hasattr(pbi, "git_options")
git_opts = pbi.git_options
assert isinstance(git_opts, GitOptions)
# Test that default values are correct
assert git_opts.submodules is False
assert git_opts.submodule_paths == []
# Test creating a new package settings with custom git options
settings_yaml = """
git_options:
submodules: true
submodule_paths:
- vendor/lib
"""
custom_settings = PackageSettings.from_string("custom-pkg", settings_yaml)
assert custom_settings.git_options.submodules is True
assert custom_settings.git_options.submodule_paths == ["vendor/lib"]
def test_package_build_info_exclusive_build(
testdata_context: context.WorkContext,
) -> None:
"""Test that PackageBuildInfo correctly exposes exclusive_build from build_options."""
# Test default package (should have exclusive_build=False by default)
req = Requirement("test-empty-pkg==1.0.0")
pbi = testdata_context.package_build_info(req)
assert pbi.exclusive_build is False
# Test creating a package settings with exclusive_build=True
settings_yaml = """
build_options:
exclusive_build: true
"""
custom_settings = PackageSettings.from_string("exclusive-pkg", settings_yaml)
assert custom_settings.build_options.exclusive_build is True
# Test PackageBuildInfo properly accesses it through build_options
import pathlib
from fromager.packagesettings import Settings, SettingsFile
# Create a temporary Settings object to test with
settings = Settings(
settings=SettingsFile(),
package_settings=[custom_settings],
variant="cpu",
patches_dir=pathlib.Path("/tmp"),
max_jobs=1,
)
custom_pbi = settings.package_build_info("exclusive-pkg")
assert custom_pbi.exclusive_build is True
def test_resolver_dist_validator() -> None:
with pytest.raises(pydantic.ValidationError):
ResolverDist(include_wheels=False, ignore_platform=True)
def test_annotation_type() -> None:
ann = Annotations(None, None)
assert not ann
assert len(ann) == 0
assert ann == {}
with pytest.raises(TypeError):
ann["key"] = "value" # type: ignore
ann = Annotations({"ka": "va", "kb": "vb"}, {"kb": "otherb", "kc": "vc"})
assert ann
assert len(ann) == 3
assert ann == {"ka": "va", "kb": "otherb", "kc": "vc"}
ann = Annotations({"t": "yes", "f": "no", "invalid": "invalid"}, {})
assert ann.getbool("t") is True
assert ann.getbool("f") is False
with pytest.raises(ValueError):
ann.getbool("invalid")
with pytest.raises(KeyError):
ann.getbool("missing")
def test_pbi_annotations(testdata_context: context.WorkContext) -> None:
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.annotations == {
"fromager.test.value": "somevalue",
"fromager.test.override": "cpu override",
}
testdata_context.settings.variant = Variant("cuda")
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.annotations == {
"fromager.test.value": "somevalue",
"fromager.test.override": "variant override",
}
testdata_context.settings.variant = Variant("rocm")
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.annotations == {
"fromager.test.value": "somevalue",
"fromager.test.override": "amd override",
}
pbi = testdata_context.settings.package_build_info(TEST_EMPTY_PKG)
assert pbi.annotations == {}
def test_use_pypi_org_metadata(testdata_context: context.WorkContext) -> None:
pbi = testdata_context.settings.package_build_info(TEST_PKG)
assert pbi.use_pypi_org_metadata
pbi = testdata_context.settings.package_build_info(TEST_EMPTY_PKG)
assert not pbi.use_pypi_org_metadata
pbi = testdata_context.settings.package_build_info(
"somepackage_without_customization"
)
assert pbi.use_pypi_org_metadata
def _make_pbi(env_yaml: str, tmp_path: pathlib.Path) -> PackageBuildInfo:
"""Create a PackageBuildInfo from inline env YAML."""
ps = PackageSettings.from_string("version-test-pkg", env_yaml)
settings = Settings(
settings=SettingsFile(),
package_settings=[ps],
variant="cpu",
patches_dir=tmp_path,
max_jobs=1,
)
return settings.package_build_info("version-test-pkg")
def test_version_env_var_raises_when_version_unknown(
tmp_path: pathlib.Path,
) -> None:
"""Using ${__version__} in env without a fallback raises when version is None.
This mirrors the git-URL bootstrap path where the version has not yet
been resolved (e.g. ``pkg @ git+https://host/repo.git@main``).
"""
pbi = _make_pbi(
"""
env:
MY_VERSION: "${__version__}"
""",
tmp_path,
)
with pytest.raises(ValueError, match="__version__"):
pbi.get_extra_environ(template_env={}, version=None)
def test_version_env_var_with_default_when_version_unknown(
tmp_path: pathlib.Path,
) -> None:
"""${__version__:-fallback} substitutes the default when version is None."""
pbi = _make_pbi(
"""
env:
MY_VERSION: "${__version__:-unresolved}"
""",
tmp_path,
)
result = pbi.get_extra_environ(template_env={}, version=None)
assert result["MY_VERSION"] == "unresolved"
assert "__version__" not in result
def test_version_none_no_reference(
tmp_path: pathlib.Path,
) -> None:
"""version=None works when no env vars reference __version__."""
pbi = _make_pbi(
"""
env:
FOO: "bar"
""",
tmp_path,
)
result = pbi.get_extra_environ(template_env={}, version=None)
assert result["FOO"] == "bar"
assert "__version__" not in result