-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathtest_dynamic_metadata.py
349 lines (271 loc) · 10.9 KB
/
test_dynamic_metadata.py
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
from __future__ import annotations
import importlib
import shutil
import subprocess
import sys
import textwrap
import types
import zipfile
from pathlib import Path
from typing import Any
import pytest
from packaging.version import Version
from scikit_build_core._compat import tomllib
from scikit_build_core._vendor import pyproject_metadata
from scikit_build_core.build import build_wheel
from scikit_build_core.build.metadata import get_standard_metadata
from scikit_build_core.builder.get_requires import GetRequires
from scikit_build_core.metadata import regex
from scikit_build_core.settings.skbuild_read_settings import SettingsReader
from pathutils import contained
# these are mock plugins returning known results
# it turns out to be easier to create EntryPoint objects pointing to real
# functions than to mock them.
def ep_version(
field: str,
_settings: dict[str, object] | None = None,
) -> str:
assert field == "version"
return "0.0.2"
def ep_readme(
field: str,
_settings: dict[str, object] | None = None,
) -> str | dict[str, str | None]:
assert field == "readme"
return {
"content-type": "text/x-rst",
"text": "Some text",
}
def ep_license(
field: str,
_settings: dict[str, object] | None = None,
) -> dict[str, str | None]:
assert field == "license"
return {"text": "MIT License"}
def ep_dual(
_field: str,
_settings: dict[str, object] | None = None,
) -> str | dict[str, str | None]:
# Fields intentionally not checked to verify backend error thrown
if _field == "version":
return "0.3"
if _field == "license":
return {"text": "BSD License"}
msg = f"Invalid field {_field}"
raise KeyError(msg)
original_loader = importlib.import_module
def special_loader(name: str, *args: Any, **kwargs: Any) -> Any:
if name == "test_version":
test_version = types.ModuleType("test_version")
test_version.dynamic_metadata = ep_version # type: ignore[attr-defined]
return test_version
if name == "test_readme":
test_readme = types.ModuleType("test_readme")
test_readme.dynamic_metadata = ep_readme # type: ignore[attr-defined]
return test_readme
if name == "test_license":
test_license = types.ModuleType("test_license")
test_license.dynamic_metadata = ep_license # type: ignore[attr-defined]
return test_license
if name == "test_dual":
test_dual = types.ModuleType("test_dual")
test_dual.dynamic_metadata = ep_dual # type: ignore[attr-defined]
return test_dual
return original_loader(name, *args, **kwargs)
@pytest.fixture
def mock_entry_points(monkeypatch):
monkeypatch.setattr(importlib, "import_module", special_loader)
@pytest.mark.usefixtures("mock_entry_points", "package_dynamic_metadata")
def test_dynamic_metadata():
with Path("pyproject.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
metadata = get_standard_metadata(pyproject, settings)
assert str(metadata.version) == "0.0.2"
assert metadata.license == pyproject_metadata.License("MIT License", None)
assert metadata.readme == pyproject_metadata.Readme("Some text", None, "text/x-rst")
@pytest.mark.usefixtures("package_dynamic_metadata")
def test_plugin_metadata():
reason_msg = (
"install hatch-fancy-pypi-readme and setuptools-scm to test the "
"dynamic metadata plugins"
)
pytest.importorskip("hatch_fancy_pypi_readme", reason=reason_msg)
pytest.importorskip("setuptools_scm", reason=reason_msg)
if shutil.which("git") is None:
pytest.skip("git is not installed")
shutil.copy("plugin_project.toml", "pyproject.toml")
subprocess.run(["git", "init", "--initial-branch=main"], check=True)
subprocess.run(["git", "config", "user.name", "bot"], check=True)
subprocess.run(["git", "config", "user.email", "[email protected]"], check=True)
subprocess.run(["git", "add", "pyproject.toml"], check=True)
subprocess.run(["git", "commit", "-m", "initial commit"], check=True)
subprocess.run(["git", "tag", "v0.1.0", "-m", "initial commint"], check=True)
with Path("pyproject.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
metadata = get_standard_metadata(pyproject, settings)
assert str(metadata.version) == "0.1.0"
assert metadata.readme == pyproject_metadata.Readme(
"Fragment #1Fragment #2", None, "text/x-rst"
)
assert set(GetRequires().dynamic_metadata()) == {
"hatch-fancy-pypi-readme>=22.3",
"setuptools-scm",
}
@pytest.mark.usefixtures("package_dynamic_metadata")
def test_faulty_metadata():
with Path("faulty_project.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
with pytest.raises(KeyError):
get_standard_metadata(pyproject, settings)
@pytest.mark.usefixtures("package_dynamic_metadata")
def test_local_plugin_metadata():
with Path("local_pyproject.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
metadata = get_standard_metadata(pyproject, settings)
assert metadata.version == Version("3.2.1")
@pytest.mark.usefixtures("package_dynamic_metadata")
def test_warn_metadata():
with Path("warn_project.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
with pytest.raises(ModuleNotFoundError):
get_standard_metadata(pyproject, settings)
@pytest.mark.usefixtures("package_dynamic_metadata")
def test_fail_experimental_metadata():
with Path("warn_project.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(
pyproject, {"experimental": "false"}, state="metadata_wheel"
)
with pytest.raises(SystemExit) as exc:
settings_reader.validate_may_exit()
(value,) = exc.value.args
assert value == 7
@pytest.mark.usefixtures("mock_entry_points", "package_dynamic_metadata")
def test_dual_metadata():
with Path("dual_project.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
metadata = get_standard_metadata(pyproject, settings)
assert str(metadata.version) == "0.3"
assert metadata.license == pyproject_metadata.License("BSD License", None)
with Path("faulty_dual_project.toml").open("rb") as ft:
pyproject = tomllib.load(ft)
settings_reader = SettingsReader(pyproject, {}, state="metadata_wheel")
settings = settings_reader.settings
settings_reader.validate_may_exit()
with pytest.raises(KeyError):
get_standard_metadata(pyproject, settings)
@pytest.mark.compile
@pytest.mark.configure
@pytest.mark.usefixtures("mock_entry_points", "package_dynamic_metadata")
def test_pep517_wheel(virtualenv):
dist = Path("dist")
out = build_wheel("dist")
(wheel,) = dist.glob("dynamic-0.0.2-*.whl")
assert wheel == dist / out
virtualenv.install(wheel)
if sys.version_info >= (3, 8):
license = virtualenv.execute(
"from importlib.metadata import metadata; print(metadata('dynamic')['License'])"
)
assert license == "MIT License"
with zipfile.ZipFile(wheel) as zf:
file_paths = {Path(n) for n in zf.namelist()}
dynamic_pkg = {x.name for x in contained(file_paths, "dynamic")}
filtered_pkg = {x for x in dynamic_pkg if not x.startswith("_module")}
assert len(filtered_pkg) == len(dynamic_pkg) - 1
assert {"dynamic-0.0.2.dist-info", "dynamic"} == {p.parts[0] for p in file_paths}
assert {"__init__.py"} == filtered_pkg
version = virtualenv.execute("from dynamic import square; print(square(2))")
assert version == "4.0"
def test_regex(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
d = tmp_path / "test_regex"
d.mkdir()
monkeypatch.chdir(d)
with Path("__init__.py").open("w") as f:
f.write("__version__ = '0.1.0'")
regex.dynamic_metadata("version", {"input": "__init__.py"})
def test_regex_errors() -> None:
with pytest.raises(RuntimeError):
regex.dynamic_metadata("version", {})
with pytest.raises(RuntimeError, match="Only string fields supported"):
regex.dynamic_metadata("author", {"input": "x", "regex": "x"})
def test_multipart_regex(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
d = tmp_path / "test_multi_regex"
d.mkdir()
monkeypatch.chdir(d)
with Path("version.hpp").open("w") as f:
f.write(
textwrap.dedent(
"""\
#define VERSION_MAJOR 1
// Comment
#define VERSION_MINOR 2
#define VERSION_PATCH 3dev1
"""
)
)
version = regex.dynamic_metadata(
"version",
{
"input": "version.hpp",
"regex": r"""(?sx)
\#define \s+ VERSION_MAJOR \s+ (?P<major>\d+) .*?
\#define \s+ VERSION_MINOR \s+ (?P<minor>\d+) .*?
\#define \s+ VERSION_PATCH \s+ (?P<patch>\w+)
""",
"result": "{major}.{minor}.{patch}",
},
)
assert version == "1.2.3dev1"
@pytest.mark.parametrize("dev", [0, 1])
def test_regex_remove(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dev: int
) -> None:
d = tmp_path / "test_multidev_regex"
d.mkdir()
monkeypatch.chdir(d)
with Path("version.hpp").open("w") as f:
f.write(
textwrap.dedent(
f"""\
#define VERSION_MAJOR 1
// Comment
#define VERSION_MINOR 2
#define VERSION_PATCH 3
#define VERSION_DEV {dev}
"""
)
)
version = regex.dynamic_metadata(
"version",
{
"input": "version.hpp",
"regex": r"""(?sx)
\#define \s+ VERSION_MAJOR \s+ (?P<major>\d+) .*?
\#define \s+ VERSION_MINOR \s+ (?P<minor>\d+) .*?
\#define \s+ VERSION_PATCH \s+ (?P<patch>\d+) .*?
\#define \s+ VERSION_DEV \s+ (?P<dev>\d+)
""",
"result": "{major}.{minor}.{patch}dev{dev}",
"remove": r"dev0",
},
)
assert version == ("1.2.3dev1" if dev else "1.2.3")