-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest.py
More file actions
259 lines (198 loc) · 6.78 KB
/
test.py
File metadata and controls
259 lines (198 loc) · 6.78 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
import logging
import subprocess
import time
from pathlib import Path
import pytest
import requests
from inline_snapshot import snapshot
from pypi_attestations import Attestation, GitHubPublisher
from sigstore import oidc
import action
logger = logging.getLogger(__name__)
@pytest.fixture(autouse=True)
def capture_summary(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
"""
Capture the GitHub Actions job summary to a temporary file.
"""
summary_path = tmp_path / "GITHUB_STEP_SUMMARY"
summary_path.touch()
monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(summary_path))
return summary_path
@pytest.fixture(scope="session")
def id_token() -> oidc.IdentityToken:
def _id_token() -> oidc.IdentityToken | None:
# GitHub loves to cache things it has no business caching.
result = subprocess.run(
[
"git",
"ls-remote",
"https://github.com/sigstore-conformance/extremely-dangerous-public-oidc-beacon",
"refs/heads/current-token",
],
capture_output=True,
text=True,
check=True,
)
ref = result.stdout.split()[0]
resp = requests.get(
f"https://raw.githubusercontent.com/sigstore-conformance/extremely-dangerous-public-oidc-beacon/{ref}/oidc-token.txt",
)
resp.raise_for_status()
id_token = resp.text.strip()
try:
return oidc.IdentityToken(id_token)
except Exception:
return None
# Try up to 10 times to get a valid token, waiting 3 seconds between attempts.
for n in range(10):
token = _id_token()
if token is not None:
return token
else:
logger.warning(f"Waiting for valid OIDC identity token, try {n}...")
time.sleep(3)
raise RuntimeError("Failed to obtain OIDC identity token for tests")
@pytest.fixture
def sampleproject(tmp_path: Path) -> Path:
"""
Create a sample Python project with a distribution file.
"""
project_dir = tmp_path / "sampleproject"
project_dir.mkdir()
pyproject = project_dir / "pyproject.toml"
pyproject.write_text("""
name = "astral-sh-attest-action-test-sampleproject"
version = "0.1.0"
description = "Who's wants to know?"
requires-python = ">=3.10"
""")
hello_py = project_dir / "hello.py"
hello_py.write_text("""
def main():
print("Hello, world!")
""")
return project_dir
def test_get_input(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("ATTEST_ACTION_INPUT_FOO", "expected")
assert action._get_input("foo") == "expected"
def test_get_path_patterns(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("ATTEST_ACTION_INPUT_PATHS", "dist/* another/** third/")
patterns = action._get_path_patterns()
assert patterns == {"dist/*", "another/**", "third/*"}
# Deduplicates patterns / files.
monkeypatch.setenv("ATTEST_ACTION_INPUT_PATHS", "dist/* dist/* another/")
patterns = action._get_path_patterns()
assert patterns == {"dist/*", "another/*"}
monkeypatch.setenv("ATTEST_ACTION_INPUT_PATHS", "a a b b c")
patterns = action._get_path_patterns()
assert patterns == {"a", "b", "c"}
def test_unroll_files_recursive(tmp_path: Path) -> None:
root = tmp_path / "dists"
root.mkdir()
(root / "top.tar.gz").touch()
sub = root / "nested"
sub.mkdir()
(sub / "deep.whl").touch()
# ** should match files at all depths.
files = action._unroll_files({str(root / "**")})
assert files == {root / "top.tar.gz", sub / "deep.whl"}
# * should only match files at the top level.
files = action._unroll_files({str(root / "*")})
assert files == {root / "top.tar.gz"}
def test_attest(sampleproject: Path, id_token: oidc.IdentityToken) -> None:
subprocess.run(["uv", "build"], cwd=sampleproject, check=True)
dist_dir = sampleproject / "dist"
patterns = {str(dist_dir / "*")}
dists = action._collect_dists(patterns)
assert len(dists) == 2 # sdist and wheel
action._attest(
dists,
id_token,
overwrite=False,
)
for dist_path, _ in dists:
attestation_path = dist_path.with_name(f"{dist_path.name}.publish.attestation")
assert attestation_path.exists()
def test_attest_overwrite_fails(
sampleproject: Path,
id_token: oidc.IdentityToken,
) -> None:
subprocess.run(["uv", "build"], cwd=sampleproject, check=True)
dist_dir = sampleproject / "dist"
patterns = {str(dist_dir / "*")}
dists = action._collect_dists(patterns)
assert len(dists) == 2 # sdist and wheel
action._attest(
dists,
id_token,
overwrite=False,
)
with pytest.raises(SystemExit):
action._attest(
dists,
id_token,
overwrite=False,
)
def test_attest_overwrite_succeeds(
sampleproject: Path,
id_token: oidc.IdentityToken,
) -> None:
subprocess.run(["uv", "build"], cwd=sampleproject, check=True)
dist_dir = sampleproject / "dist"
patterns = {str(dist_dir / "*")}
dists = action._collect_dists(patterns)
assert len(dists) == 2 # sdist and wheel
action._attest(
dists,
id_token,
overwrite=False,
)
# This should succeed without error.
action._attest(
dists,
id_token,
overwrite=True,
)
def test_attest_verify(
sampleproject: Path,
id_token: oidc.IdentityToken,
) -> None:
subprocess.run(["uv", "build"], cwd=sampleproject, check=True)
dist_dir = sampleproject / "dist"
patterns = {str(dist_dir / "*")}
dists = action._collect_dists(patterns)
assert len(dists) == 2 # sdist and wheel
action._attest(
dists,
id_token,
overwrite=False,
)
for dist_path, dist in dists:
attestation_path = dist_path.with_name(f"{dist_path.name}.publish.attestation")
assert attestation_path.exists()
attestation = Attestation.model_validate_json(attestation_path.read_bytes())
identity = GitHubPublisher(
repository="sigstore-conformance/extremely-dangerous-public-oidc-beacon",
workflow="extremely-dangerous-oidc-beacon.yml",
)
attestation.verify(
identity=identity,
dist=dist,
offline=True,
)
def test_attest_no_dists(
id_token: oidc.IdentityToken,
capture_summary: Path,
) -> None:
with pytest.raises(SystemExit):
action._attest(
[],
id_token,
overwrite=False,
)
assert capture_summary.read_text() == snapshot("""\
### ❌ Fatal: No distributions to attest
No valid Python distributions were collected from the specified paths.
> [!TIP]
> Ensure that the `paths` input points to valid distribution files.
""")