-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
649 lines (526 loc) · 21.3 KB
/
Copy pathtests.py
File metadata and controls
649 lines (526 loc) · 21.3 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
# ruff: noqa: S101
import argparse
import shutil
import subprocess
import sys
import tempfile
from collections.abc import Generator
from os import environ
from pathlib import Path
from urllib.request import urlopen
import pytest
sys.path.insert(0, str(Path(__file__).parent))
import git_evtag_py as evtag
V101_CSUM = (
"3973d3ad28248971e6c870936012f44c512df1700cde0cf80713aced9a134fff"
"0f71eb99d87d45fd8b6c7a6fa32ec095b3bc529d09e7774ca07cefd53b1ee802"
)
V108_CSUM = (
"b078bd1616243c65346ff47370ddf1f2e99dda350c9093b079f24647d122d38"
"5d8a5080a1645716dcec7530690f5537fc33f9c44e06ed3d265ff74fddf0cca74"
)
V101_TAG_LINE = f"Git-EVTag-Py-v0-SHA512: {V101_CSUM}"
V108_TAG_LINE = f"Git-EVTag-v0-SHA512: {V108_CSUM}"
V101_SHA = "295a273a2af003e57edd369f7f7e83155c36a074"
REPO_URL = "https://github.com/bbhtt/git-evtag-py.git"
def _run_git(repo: Path, *args: str) -> str:
return subprocess.run(
["git", *args],
cwd=repo,
check=True,
capture_output=True,
text=True,
).stdout.strip()
def _make_repo(tmp: Path) -> Path:
repo = tmp / "repo"
repo.mkdir()
_run_git(tmp, "init", str(repo))
_run_git(repo, "config", "user.name", "Test User")
_run_git(repo, "config", "user.email", "test@example.com")
(repo / "file.txt").write_text("hello\n")
_run_git(repo, "add", ".")
_run_git(repo, "commit", "-m", "init")
return repo
def _build_tree_entry(mode: str, name: str, sha_hex: str) -> bytes:
return f"{mode} {name}\0".encode() + bytes.fromhex(sha_hex)
_GPG_KEY_URL = (
"https://keyserver.ubuntu.com/pks/lookup"
"?op=get&search=0xd26d753395009db2b3b260940c3251a24745e484"
)
def _import_gpg_key() -> None:
local = Path(__file__).parent / "pub_key.asc"
key_url = environ.get("KEY_URL", _GPG_KEY_URL)
if local.exists():
key_data = local.read_text()
else:
with urlopen(key_url) as response: # noqa: S310
key_data = response.read().decode("utf-8")
subprocess.run(
["gpg", "--import"],
input=key_data,
text=True,
check=True,
capture_output=True,
)
def _make_args(**kwargs: object) -> argparse.Namespace:
defaults: dict[str, object] = {
"rev": None,
"verify": None,
"sign": None,
"tag_msg": None,
"in_place": False,
}
defaults.update(kwargs)
return argparse.Namespace(**defaults)
class TestCheckGitVersion:
def _make_result(self, stdout: str) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout)
def test_sufficient_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
evtag, "run_git", lambda *_, **__: self._make_result("git version 2.9.0\n")
)
assert evtag.check_git_version()
def test_newer_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
evtag, "run_git", lambda *_, **__: self._make_result("git version 2.47.1\n")
)
assert evtag.check_git_version()
def test_too_old(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
evtag, "run_git", lambda *_, **__: self._make_result("git version 1.8.3\n")
)
assert not evtag.check_git_version()
class TestParseTreeContent:
def test_single_blob(self) -> None:
sha = "a" * 40
assert evtag.parse_tree_content(
_build_tree_entry("100644", "README.md", sha)
) == [("blob", sha, "README.md")]
def test_single_tree(self) -> None:
sha = "b" * 40
assert evtag.parse_tree_content(_build_tree_entry("40000", "src", sha)) == [
("tree", sha, "src")
]
def test_submodule_commit(self) -> None:
sha = "c" * 40
assert evtag.parse_tree_content(_build_tree_entry("160000", "sub", sha)) == [
("commit", sha, "sub")
]
def test_executable_blob(self) -> None:
sha = "d" * 40
assert evtag.parse_tree_content(_build_tree_entry("100755", "run.sh", sha)) == [
("blob", sha, "run.sh")
]
def test_symlink_blob(self) -> None:
sha = "e" * 40
assert evtag.parse_tree_content(_build_tree_entry("120000", "link", sha)) == [
("blob", sha, "link")
]
def test_multiple_entries(self) -> None:
sha1, sha2 = "a" * 40, "b" * 40
content = _build_tree_entry("100644", "a.txt", sha1) + _build_tree_entry(
"40000", "dir", sha2
)
assert evtag.parse_tree_content(content) == [
("blob", sha1, "a.txt"),
("tree", sha2, "dir"),
]
class TestRunCommand:
def test_success_capture(self) -> None:
result = evtag.run_command(["echo", "hi"], capture_output=True)
assert result is not None
assert result.stdout.strip() == "hi"
def test_failure_returns_none(self) -> None:
assert evtag.run_command(["false"]) is None
def test_cwd_respected(self, tmp_path: Path) -> None:
result = evtag.run_command(["pwd"], capture_output=True, cwd=tmp_path)
assert result is not None
assert result.stdout.strip() == str(tmp_path)
def test_warn_does_not_raise(self) -> None:
assert evtag.run_command(["false"], warn=True) is None
def test_no_capture_returns_result(self) -> None:
assert evtag.run_command(["true"]) is not None
class TestRunGit:
def test_run_git(self) -> None:
result = evtag.run_git(["--version"], capture_output=True)
assert result is not None
assert "git version " in result.stdout
def test_invalid_subcommand(self, tmp_path: Path) -> None:
assert evtag.run_git(["not-a-real-subcommand"], repo=tmp_path) is None
def test_repo_arg_sets_cwd(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
result = evtag.run_git(["rev-parse", "HEAD"], repo=repo, capture_output=True)
assert result is not None
assert len(result.stdout.strip()) == 40
class TestIsGitDirectory:
def test_nonexistent(self, tmp_path: Path) -> None:
assert not evtag.is_git_directory(tmp_path / "nope")
def test_plain_directory(self, tmp_path: Path) -> None:
assert not evtag.is_git_directory(tmp_path)
def test_git_repo(self, tmp_path: Path) -> None:
assert evtag.is_git_directory(_make_repo(tmp_path))
class TestValidateArgs:
def test_no_args(self) -> None:
assert evtag.validate_args(_make_args())
def test_verify_and_sign_invalid(self) -> None:
assert not evtag.validate_args(_make_args(verify="v1", sign="v2"))
def test_rev_with_verify_invalid(self) -> None:
assert not evtag.validate_args(_make_args(rev="HEAD", verify="v1"))
def test_rev_with_sign_invalid(self) -> None:
assert not evtag.validate_args(_make_args(rev="HEAD", sign="v1"))
def test_tag_msg_without_sign_invalid(self) -> None:
assert not evtag.validate_args(_make_args(tag_msg="msg"))
def test_tag_msg_with_sign_valid(self) -> None:
assert evtag.validate_args(_make_args(sign="v1", tag_msg="msg"))
def test_sign_alone(self) -> None:
assert evtag.validate_args(_make_args(sign="v1"))
def test_verify_alone(self) -> None:
assert evtag.validate_args(_make_args(verify="v1"))
def test_rev_alone(self) -> None:
assert evtag.validate_args(_make_args(rev="HEAD"))
def test_in_place_alone(self) -> None:
assert evtag.validate_args(_make_args(in_place=True))
class TestEnsureGitRev:
def test_head(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
sha = evtag.ensure_git_rev("HEAD", repo)
assert sha is not None
assert len(sha) == 40
def test_invalid_rev(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
assert evtag.ensure_git_rev("refs/tags/nonexistent", repo) is None
class TestComputeChecksum:
def test_returns_sha512_hex(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
csum = evtag.compute_checksum(repo, "HEAD")
assert csum is not None
assert len(csum) == 128
assert all(c in "0123456789abcdef" for c in csum)
def test_deterministic(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
assert evtag.compute_checksum(repo, "HEAD") == evtag.compute_checksum(
repo, "HEAD"
)
def test_invalid_rev_returns_none(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
assert evtag.compute_checksum(repo, "refs/tags/nonexistent") is None
def test_changes_between_commits(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
csum1 = evtag.compute_checksum(repo, "HEAD")
(repo / "extra.txt").write_text("more\n")
_run_git(repo, "add", ".")
_run_git(repo, "commit", "-m", "second")
assert evtag.compute_checksum(repo, "HEAD") != csum1
class TestPrepareClone:
def test_in_place_returns_src(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
result = evtag.prepare_clone(repo, "HEAD", in_place=True)
assert result is not None
tmpdir, work_repo = result
assert tmpdir is None
assert work_repo == repo
def test_clone_creates_repo(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
result = evtag.prepare_clone(repo, "HEAD", in_place=False)
assert result is not None
tmpdir, work_repo = result
assert tmpdir is not None
assert work_repo != repo
assert (work_repo / ".git").is_dir()
tmpdir.cleanup()
def test_invalid_rev_returns_none(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
assert (
evtag.prepare_clone(repo, "refs/tags/nonexistent", in_place=False) is None
)
class TestExtractChecksumFromTag:
def test_missing_tag_returns_none(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
assert evtag.extract_checksum_from_tag(repo, "nonexistent") is None
def test_tag_without_evtag_returns_none(self, tmp_path: Path) -> None:
repo = _make_repo(tmp_path)
subprocess.run(
["git", "tag", "-a", "v-plain", "-m", "no evtag here"],
cwd=repo,
check=True,
capture_output=True,
env={**environ, "EVTAG_NO_GPG_SIGN": "true"},
)
assert evtag.extract_checksum_from_tag(repo, "v-plain") is None
def _find_repo() -> Path | None:
candidate = Path(__file__).parent.resolve()
while candidate != candidate.parent:
if (candidate / ".git").is_dir():
result = subprocess.run(
["git", "remote", "get-url", "origin"],
cwd=candidate,
capture_output=True,
text=True,
check=False,
)
if "git-evtag-py" in result.stdout:
return candidate
candidate = candidate.parent
return None
@pytest.fixture(scope="module")
def remote_repo() -> Generator[tuple[Path, str], None, None]:
self_repo = _find_repo()
if self_repo is not None:
tmpdir = tempfile.mkdtemp()
repo = Path(tmpdir) / "test_repo"
_run_git(Path(tmpdir), "clone", "--no-local", str(self_repo), str(repo))
_run_git(repo, "config", "user.name", "bbhtt")
_run_git(repo, "config", "user.email", "bbhtt.zn0i8@slmail.me")
yield repo, tmpdir
shutil.rmtree(tmpdir)
return
tmpdir = tempfile.mkdtemp()
repo = Path(tmpdir) / "test_repo"
_run_git(Path(tmpdir), "clone", REPO_URL, str(repo))
_run_git(repo, "config", "user.name", "bbhtt")
_run_git(repo, "config", "user.email", "bbhtt.zn0i8@slmail.me")
yield repo, tmpdir
shutil.rmtree(tmpdir)
@pytest.fixture(scope="module")
def gpg_key() -> None:
_import_gpg_key()
@pytest.mark.integration
class TestIntegrationCompute:
def test_at_v101(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "v1.0.1")
assert _run_git(repo, "rev-parse", "HEAD") == V101_SHA
assert evtag.compute_checksum(repo, "HEAD") == V101_CSUM
def test_rev_tag(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "main")
assert evtag.compute_checksum(repo, "v1.0.1") == V101_CSUM
def test_rev_sha(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "main")
assert evtag.compute_checksum(repo, V101_SHA) == V101_CSUM
def test_in_place(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "v1.0.1")
result = evtag.prepare_clone(repo, "HEAD", in_place=True)
assert result is not None
_, work_repo = result
assert evtag.compute_checksum(work_repo, "HEAD") == V101_CSUM
def test_at_v108(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "v1.0.8")
assert evtag.compute_checksum(repo, "HEAD") == V108_CSUM
@pytest.mark.integration
class TestIntegrationVerify:
def test_signed_tag_passes(
self,
remote_repo: tuple[Path, str],
gpg_key: None, # noqa: ARG002
) -> None:
repo, _ = remote_repo
tag_csum = evtag.extract_checksum_from_tag(repo, "v1.0.8")
assert tag_csum is not None
result = evtag.prepare_clone(repo, "v1.0.8", in_place=True)
assert result is not None
_, work_repo = result
calc = evtag.compute_checksum(work_repo, "v1.0.8")
assert evtag.verify_tag(repo, "v1.0.8", tag_csum, calc or "")
def test_mismatched_checksum_fails(
self,
remote_repo: tuple[Path, str],
gpg_key: None, # noqa: ARG002
) -> None:
repo, _ = remote_repo
tag_csum = evtag.extract_checksum_from_tag(repo, "v1.0.8")
assert tag_csum is not None
assert not evtag.verify_tag(repo, "v1.0.8", tag_csum, "deadbeef" * 16)
@pytest.mark.integration
class TestIntegrationRelativeSubmodule:
def test_relative_submodule_url_resolves(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GIT_CONFIG_COUNT", "1")
monkeypatch.setenv("GIT_CONFIG_KEY_0", "protocol.file.allow")
monkeypatch.setenv("GIT_CONFIG_VALUE_0", "always")
sub_remote = tmp_path / "sub_remote"
sub_remote.mkdir()
_run_git(sub_remote, "init", "--bare", str(sub_remote))
sub_work = tmp_path / "sub_work"
sub_work.mkdir()
_run_git(tmp_path, "clone", str(sub_remote), str(sub_work))
_run_git(sub_work, "config", "user.name", "Test User")
_run_git(sub_work, "config", "user.email", "test@example.com")
(sub_work / "sub.txt").write_text("sub\n")
_run_git(sub_work, "add", ".")
_run_git(sub_work, "commit", "-m", "sub init")
_run_git(sub_work, "push", "origin", "HEAD:main")
_run_git(sub_remote, "symbolic-ref", "HEAD", "refs/heads/main")
sub_sha = _run_git(sub_work, "rev-parse", "HEAD")
super_remote = tmp_path / "super_remote"
super_remote.mkdir()
_run_git(super_remote, "init", "--bare", str(super_remote))
super_work = tmp_path / "super_work"
super_work.mkdir()
_run_git(tmp_path, "clone", str(super_remote), str(super_work))
_run_git(super_work, "config", "user.name", "Test User")
_run_git(super_work, "config", "user.email", "test@example.com")
(super_work / "README").write_text("init\n")
_run_git(super_work, "add", "README")
_run_git(super_work, "commit", "-m", "initial")
_run_git(super_work, "push", "origin", "HEAD:main")
_run_git(super_remote, "symbolic-ref", "HEAD", "refs/heads/main")
subprocess.run(
[
"git",
"-c",
"protocol.file.allow=always",
"submodule",
"add",
str(sub_remote),
"sub",
],
cwd=super_work,
check=True,
capture_output=True,
)
gitmodules = super_work / ".gitmodules"
gitmodules.write_text(
gitmodules.read_text().replace(
str(sub_remote),
"../sub_remote",
)
)
_run_git(super_work, "add", ".")
_run_git(super_work, "commit", "-m", "add submodule")
_run_git(super_work, "push", "origin", "HEAD:main")
local_clone = tmp_path / "local_clone"
_run_git(tmp_path, "clone", str(super_remote), str(local_clone))
_run_git(local_clone, "config", "user.name", "Test User")
_run_git(local_clone, "config", "user.email", "test@example.com")
result = evtag.prepare_clone(
local_clone,
"HEAD",
in_place=False,
)
assert result is not None
tmpdir, work_repo = result
try:
sub_dir = work_repo / "sub"
assert sub_dir.is_dir()
assert (sub_dir / "sub.txt").is_file()
assert _run_git(sub_dir, "rev-parse", "HEAD") == sub_sha
finally:
if tmpdir:
tmpdir.cleanup()
@pytest.mark.integration
class TestIntegrationSign:
def test_sign_with_message(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "v1.0.1")
csum = evtag.compute_checksum(repo, "HEAD")
assert csum is not None
try:
with pytest.MonkeyPatch.context() as mp:
mp.setenv("EVTAG_NO_GPG_SIGN", "true")
assert evtag.sign_tree_checksum(
repo, "v-test-unit", csum, tag_msg="Test sign message"
)
lines = {
line.strip()
for line in _run_git(repo, "show", "v-test-unit").splitlines()
}
assert "Test sign message" in lines
assert any(line.endswith(V101_CSUM) for line in lines)
finally:
subprocess.run(
["git", "tag", "-d", "v-test-unit"],
check=False,
cwd=repo,
capture_output=True,
)
def test_sign_with_file_path(
self, remote_repo: tuple[Path, str], tmp_path: Path
) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "v1.0.8")
csum = evtag.compute_checksum(repo, "HEAD")
assert csum is not None
msg_file = tmp_path / "tagmsg.txt"
exp_msg = "Test sign from file"
msg_file.write_text(exp_msg)
try:
with pytest.MonkeyPatch.context() as mp:
mp.setenv("EVTAG_NO_GPG_SIGN", "true")
assert evtag.sign_tree_checksum(
repo, "v-test-file", csum, tag_msg=str(msg_file)
)
lines = {
line.strip()
for line in _run_git(repo, "show", "v-test-file").splitlines()
}
assert exp_msg in lines
assert any(line.endswith(V108_CSUM) for line in lines)
finally:
subprocess.run(
["git", "tag", "-d", "v-test-file"],
check=False,
cwd=repo,
capture_output=True,
)
def test_sign_existing_tag_fails(self, remote_repo: tuple[Path, str]) -> None:
repo, _ = remote_repo
csum = evtag.compute_checksum(repo, "HEAD")
assert csum is not None
with pytest.MonkeyPatch.context() as mp:
mp.setenv("EVTAG_NO_GPG_SIGN", "true")
assert not evtag.sign_tree_checksum(repo, "v1.0.8", csum, tag_msg="fail")
def test_sign_with_local_gpg_key(
self,
remote_repo: tuple[Path, str],
gpg_key: None, # noqa: ARG002
) -> None:
repo, _ = remote_repo
_run_git(repo, "checkout", "v1.0.1")
result = subprocess.run(
["gpg", "--list-secret-keys", "--with-colons"],
capture_output=True,
text=True,
check=True,
)
key_id: str | None = None
for line in result.stdout.splitlines():
if line.startswith("sec"):
parts = line.split(":")
if len(parts) > 4 and parts[4]:
key_id = parts[4]
break
if not key_id:
pytest.skip("No local GPG secret key available")
_run_git(repo, "config", "user.signingkey", key_id)
csum = evtag.compute_checksum(repo, "HEAD")
assert csum is not None
try:
assert evtag.sign_tree_checksum(
repo, "v-test-gpg", csum, tag_msg="GPG sign test"
)
verify = subprocess.run(
["git", "tag", "-v", "v-test-gpg"],
check=False,
cwd=repo,
capture_output=True,
text=True,
)
assert verify.returncode == 0
lines = {
line.strip()
for line in _run_git(repo, "show", "v-test-gpg").splitlines()
}
assert "GPG sign test" in lines
assert any(line.endswith(V101_CSUM) for line in lines)
finally:
subprocess.run(
["git", "tag", "-d", "v-test-gpg"],
check=False,
cwd=repo,
capture_output=True,
)