-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtest_git_interface.py
More file actions
377 lines (317 loc) · 12.1 KB
/
Copy pathtest_git_interface.py
File metadata and controls
377 lines (317 loc) · 12.1 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
import logging
import subprocess
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from socketsecurity.core.git_interface import Git
CI_ENVIRONMENT_VARIABLES = (
"BUILDKITE",
"BUILDKITE_BRANCH",
"BUILDKITE_COMMIT",
"BUILDKITE_PIPELINE_DEFAULT_BRANCH",
"BUILDKITE_PULL_REQUEST",
"BUILDKITE_PULL_REQUEST_BASE_BRANCH",
"GITHUB_BASE_REF",
"GITHUB_EVENT_BEFORE",
"GITHUB_EVENT_NAME",
"GITHUB_HEAD_REF",
"GITHUB_REF",
"GITHUB_SHA",
"CI_COMMIT_BRANCH",
"CI_COMMIT_SHA",
"CI_DEFAULT_BRANCH",
"CI_MERGE_REQUEST_SOURCE_BRANCH_NAME",
"CI_MERGE_REQUEST_TARGET_BRANCH_NAME",
"BITBUCKET_BRANCH",
"BITBUCKET_COMMIT",
"BITBUCKET_PR_DESTINATION_BRANCH",
"BITBUCKET_PR_ID",
)
@pytest.fixture(autouse=True)
def clear_ci_environment(monkeypatch):
for variable in CI_ENVIRONMENT_VARIABLES:
monkeypatch.delenv(variable, raising=False)
def _git(path, *args):
return subprocess.run(
["git", *args],
cwd=path,
check=True,
capture_output=True,
text=True,
).stdout.strip()
@pytest.fixture
def pull_request_repo(tmp_path):
path = tmp_path / "repo"
path.mkdir()
_git(path, "init", "-b", "main")
_git(path, "config", "user.name", "Socket Test")
(path / "README.md").write_text("base\n", encoding="utf-8")
_git(path, "add", "README.md")
_git(path, "commit", "-m", "base")
_git(path, "checkout", "-b", "feature")
(path / "package.json").write_text("{}\n", encoding="utf-8")
_git(path, "add", "package.json")
_git(path, "commit", "-m", "add manifest")
return path
@pytest.mark.parametrize(
("environment", "expected_branch", "expected_source"),
[
(
{
"BUILDKITE": "true",
"BUILDKITE_BRANCH": "feature",
"BUILDKITE_PULL_REQUEST": "123",
"BUILDKITE_PULL_REQUEST_BASE_BRANCH": "main",
},
"feature",
"buildkite-pr",
),
(
{
"GITHUB_EVENT_NAME": "pull_request",
"GITHUB_BASE_REF": "main",
"GITHUB_HEAD_REF": "feature",
"GITHUB_REF": "refs/pull/123/merge",
},
"feature",
"github-pr",
),
(
{
"CI_MERGE_REQUEST_SOURCE_BRANCH_NAME": "feature",
"CI_MERGE_REQUEST_TARGET_BRANCH_NAME": "main",
},
"feature",
"gitlab-mr",
),
(
{
"BITBUCKET_BRANCH": "feature",
"BITBUCKET_PR_DESTINATION_BRANCH": "main",
"BITBUCKET_PR_ID": "123",
},
"feature",
"bitbucket-pr",
),
],
)
def test_pull_request_context_uses_local_refs_without_fetch(
pull_request_repo, monkeypatch, mocker, caplog,
environment, expected_branch, expected_source,
):
head_sha = _git(pull_request_repo, "rev-parse", "HEAD")
sha_variable = {
"buildkite-pr": "BUILDKITE_COMMIT",
"github-pr": "GITHUB_SHA",
"gitlab-mr": "CI_COMMIT_SHA",
"bitbucket-pr": "BITBUCKET_COMMIT",
}[expected_source]
environment[sha_variable] = head_sha
for name, value in environment.items():
monkeypatch.setenv(name, value)
fetch = mocker.patch.object(
Git,
"_fetch_ref",
side_effect=AssertionError("unexpected fetch"),
)
mocker.patch.object(Git, "ensure_safe_directory")
with caplog.at_level(logging.INFO, logger="socketdev"):
repository = Git(str(pull_request_repo))
assert repository.branch == expected_branch
assert repository.changed_files == ["package.json"]
assert repository.is_default_branch is False
fetch.assert_not_called()
assert any(
f"source={expected_source}" in record.message
for record in caplog.records
)
assert any(
"Git initialization completed" in record.message
for record in caplog.records
)
def test_buildkite_native_context_wins_over_github_compatibility_shims(
pull_request_repo, monkeypatch, mocker
):
head_sha = _git(pull_request_repo, "rev-parse", "HEAD")
monkeypatch.setenv("BUILDKITE", "true")
monkeypatch.setenv("BUILDKITE_BRANCH", "feature")
monkeypatch.setenv("BUILDKITE_COMMIT", head_sha)
monkeypatch.setenv("BUILDKITE_PULL_REQUEST", "123")
monkeypatch.setenv("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "main")
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
monkeypatch.setenv("GITHUB_BASE_REF", "wrong-base")
monkeypatch.setenv("GITHUB_HEAD_REF", "wrong-head")
mocker.patch.object(
Git,
"_fetch_ref",
side_effect=AssertionError("unexpected fetch"),
)
mocker.patch.object(Git, "ensure_safe_directory")
repository = Git(str(pull_request_repo))
assert repository.changed_files == ["package.json"]
def test_regular_initialization_never_fetches_all(pull_request_repo, mocker):
fetch = mocker.patch.object(
Git,
"_fetch_ref",
side_effect=AssertionError("unexpected fetch"),
)
mocker.patch.object(Git, "ensure_safe_directory")
repository = Git(str(pull_request_repo))
assert repository.commit_str == _git(pull_request_repo, "rev-parse", "HEAD")
assert repository.changed_files == ["package.json"]
fetch.assert_not_called()
def test_detached_head_uses_buildkite_branch_and_commit(pull_request_repo, monkeypatch, mocker):
head_sha = _git(pull_request_repo, "rev-parse", "HEAD")
_git(pull_request_repo, "checkout", "--detach", head_sha)
monkeypatch.setenv("BUILDKITE", "true")
monkeypatch.setenv("BUILDKITE_BRANCH", "feature")
monkeypatch.setenv("BUILDKITE_COMMIT", head_sha)
monkeypatch.setenv("BUILDKITE_PULL_REQUEST", "123")
monkeypatch.setenv("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "main")
mocker.patch.object(
Git,
"_fetch_ref",
side_effect=AssertionError("unexpected fetch"),
)
mocker.patch.object(Git, "ensure_safe_directory")
repository = Git(str(pull_request_repo))
assert repository.commit_str == head_sha
assert repository.branch == "feature"
assert repository.changed_files == ["package.json"]
def test_missing_base_ref_fetches_only_that_ref(
pull_request_repo, monkeypatch, mocker, caplog
):
head_sha = _git(pull_request_repo, "rev-parse", "HEAD")
monkeypatch.setenv("BUILDKITE_BRANCH", "feature")
monkeypatch.setenv("BUILDKITE_COMMIT", head_sha)
monkeypatch.setenv("BUILDKITE_PULL_REQUEST", "123")
monkeypatch.setenv("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "remote-main")
mocker.patch.object(Git, "ensure_safe_directory")
base_sha = _git(pull_request_repo, "rev-parse", "main")
fetch = mocker.patch.object(Git, "_fetch_ref", return_value=base_sha)
with caplog.at_level(logging.INFO, logger="socketdev"):
repository = Git(str(pull_request_repo))
fetch.assert_called_once_with(
"remote-main",
"Buildkite pull-request base ref missing",
)
assert repository.changed_files == ["package.json"]
def test_targeted_fetch_never_uses_all():
repository = Git.__new__(Git)
repository.repo = MagicMock()
repository._fetched_ref_commits = {}
main_sha = "a" * 40
repository.repo.commit.return_value = SimpleNamespace(hexsha=main_sha)
result = repository._fetch_ref("main", "test")
repository.repo.git.fetch.assert_called_once_with("origin", "main")
assert "--all" not in repository.repo.git.fetch.call_args.args
assert result == main_sha
@pytest.mark.parametrize(
("value", "expected"),
[(None, False), ("", False), ("false", False), ("False", False), ("0", True), ("123", True)],
)
def test_buildkite_pull_request_detection(value, expected):
assert Git._is_buildkite_pull_request(value) is expected
@pytest.fixture
def commit_range_repo(tmp_path):
"""A manifest changes mid-range, then a source-only commit lands on top of it."""
path = tmp_path / "range-repo"
path.mkdir()
_git(path, "init", "-b", "main")
_git(path, "config", "user.name", "Socket Test")
(path / "README.md").write_text("base\n", encoding="utf-8")
_git(path, "add", "README.md")
_git(path, "commit", "-m", "base")
base_sha = _git(path, "rev-parse", "HEAD")
_git(path, "checkout", "-b", "feature")
(path / "pom.xml").write_text("<project/>\n", encoding="utf-8")
_git(path, "add", "pom.xml")
_git(path, "commit", "-m", "add dependency")
manifest_sha = _git(path, "rev-parse", "HEAD")
(path / "App.java").write_text("class App {}\n", encoding="utf-8")
_git(path, "add", "App.java")
_git(path, "commit", "-m", "source only")
return SimpleNamespace(path=path, base_sha=base_sha, manifest_sha=manifest_sha)
def test_head_commit_alone_misses_a_manifest_changed_earlier_in_the_range(
commit_range_repo, mocker,
):
mocker.patch.object(Git, "ensure_safe_directory")
repository = Git(str(commit_range_repo.path))
# Without a stated base the range is unknown, so only the tip commit is read.
assert repository.changed_files == ["App.java"]
def test_explicit_base_commit_covers_the_whole_range(
commit_range_repo, mocker, caplog,
):
mocker.patch.object(Git, "ensure_safe_directory")
with caplog.at_level(logging.INFO, logger="socketdev"):
repository = Git(
str(commit_range_repo.path),
base_commit_sha=commit_range_repo.base_sha,
)
assert sorted(repository.changed_files) == ["App.java", "pom.xml"]
assert any(
"source=explicit-base-commit" in record.message
for record in caplog.records
)
def test_explicit_base_commit_does_not_require_merge_base(
commit_range_repo, tmp_path, mocker,
):
shallow_path = tmp_path / "shallow-range-repo"
_git(
tmp_path,
"clone",
"--depth=1",
"--branch=feature",
commit_range_repo.path.as_uri(),
str(shallow_path),
)
mocker.patch.object(Git, "ensure_safe_directory")
repository = Git(
str(shallow_path),
base_commit_sha=commit_range_repo.base_sha,
)
# Fetching the base supplies both endpoint trees but does not deepen the
# feature history enough to calculate a merge base.
merge_base = subprocess.run(
["git", "merge-base", commit_range_repo.base_sha, "HEAD"],
cwd=shallow_path,
capture_output=True,
text=True,
)
assert merge_base.returncode != 0
assert sorted(repository.changed_files) == ["App.java", "pom.xml"]
def test_explicit_base_commit_takes_precedence_over_ci_environment(
commit_range_repo, monkeypatch, mocker, caplog,
):
# The CI variables describe the whole branch; the explicit base describes only
# the last commit. They disagree, so the winner is unambiguous in the result.
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
monkeypatch.setenv("GITHUB_BASE_REF", "main")
monkeypatch.setenv("GITHUB_HEAD_REF", "feature")
mocker.patch.object(Git, "ensure_safe_directory")
with caplog.at_level(logging.INFO, logger="socketdev"):
repository = Git(
str(commit_range_repo.path),
base_commit_sha=commit_range_repo.manifest_sha,
)
assert repository.changed_files == ["App.java"]
assert any(
"source=explicit-base-commit" in record.message
for record in caplog.records
)
def test_unresolvable_base_commit_warns_and_falls_back(
commit_range_repo, mocker, caplog,
):
mocker.patch.object(Git, "ensure_safe_directory")
fetch = mocker.patch.object(Git, "_fetch_ref", return_value=None)
with caplog.at_level(logging.WARNING, logger="socketdev"):
repository = Git(str(commit_range_repo.path), base_commit_sha="0" * 40)
# Falling back silently would hide that the comparison lost most of its range.
assert repository.changed_files == ["App.java"]
assert any(
"Could not resolve base commit" in record.message
for record in caplog.records
)
fetch.assert_called_once()