-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtest_check_links.py
More file actions
677 lines (546 loc) · 19.4 KB
/
Copy pathtest_check_links.py
File metadata and controls
677 lines (546 loc) · 19.4 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
from __future__ import annotations
import json
import threading
from pathlib import Path
import pytest
import requests
import tools.check_links as check_links
from tools.check_links import (
CatalogLink,
LinkChecker,
LinkResult,
PinnedDNSHTTPAdapter,
SafeTargetGuard,
ThreadLocalSessions,
UnsafeTarget,
build_report,
build_session,
classify_status,
exit_code_for_report,
select_links,
)
PUBLIC_IP = "93.184.216.34"
class FakeResponse:
def __init__(self, status_code, url="https://example.com/", history=None, headers=None):
self.status_code = status_code
self.url = url
self.history = history or []
self.headers = headers or {}
self.closed = False
def close(self):
self.closed = True
class FakeSession:
def __init__(self, head, get=None):
self.head_response = head
self.get_response = get
self.calls = []
self.closed = False
def head(self, url, **kwargs):
self.calls.append(("HEAD", url, kwargs))
return self.head_response
def get(self, url, **kwargs):
self.calls.append(("GET", url, kwargs))
return self.get_response
def close(self):
self.closed = True
def guard_for(address=PUBLIC_IP):
return SafeTargetGuard(lambda _host, _port: [address])
def link():
return CatalogLink("docs", "foundations", "Docs", "https://example.com/docs")
@pytest.mark.parametrize(
("status_code", "expected"),
[
(200, "working"),
(301, "redirect"),
(403, "review"),
(408, "review"),
(425, "review"),
(429, "review"),
(503, "review"),
(404, "broken"),
],
)
def test_status_classification(status_code, expected) -> None:
assert classify_status(status_code, redirected=False) == expected
def test_redirect_history_is_preserved() -> None:
hop = FakeResponse(301, "https://example.com/old", headers={"Location": "/docs"})
response = FakeResponse(200, "https://example.com/docs")
class RedirectSession(FakeSession):
def __init__(self):
super().__init__(hop)
self.responses = iter([hop, response])
def head(self, url, **kwargs):
self.calls.append(("HEAD", url, kwargs))
return next(self.responses)
session = RedirectSession()
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
redirect_link = CatalogLink(
"docs", "foundations", "Docs", "https://example.com/old"
)
result = checker.check_one(redirect_link)
assert result.status == "redirect"
assert result.history == [
{"status_code": 301, "url": "https://example.com/old", "location": "/docs"}
]
assert hop.closed is True
def test_head_failure_falls_back_to_streaming_get_and_confirms_404() -> None:
session = FakeSession(FakeResponse(404), FakeResponse(404))
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
result = checker.check_one(link())
assert result.status == "broken"
assert result.method == "GET"
assert session.calls[1][2]["stream"] is True
def test_head_redirect_without_location_falls_back_to_get() -> None:
head = FakeResponse(301)
response = FakeResponse(200)
session = FakeSession(head, response)
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
result = checker.check_one(link())
assert result.status == "working"
assert result.method == "GET"
assert head.closed is True
assert response.closed is True
def test_get_redirect_without_location_is_fatal() -> None:
head = FakeResponse(301)
response = FakeResponse(301)
session = FakeSession(head, response)
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
result = checker.check_one(link())
assert result.status == "error"
assert "no Location" in (result.error or "")
assert head.closed is True
assert response.closed is True
def test_unsupported_redirect_status_is_fatal() -> None:
response = FakeResponse(304)
session = FakeSession(response)
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
result = checker.check_one(link())
assert result.status == "error"
assert "unsupported redirect status 304" in (result.error or "")
assert response.closed is True
@pytest.mark.parametrize("status_code", [403, 408, 425, 429, 500, 503])
def test_transient_and_access_denied_statuses_need_review(status_code) -> None:
head = FakeResponse(status_code)
session = FakeSession(head, FakeResponse(status_code))
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: session,
workers=1,
retries=0,
min_interval=0,
)
assert checker.check_one(link()).status == "review"
assert len(session.calls) == 1
assert head.closed is True
@pytest.mark.parametrize(
"url",
[
"http://localhost/admin",
"http://127.0.0.1/",
"http://169.254.169.254/latest/meta-data/",
"http://100.100.100.200/latest/meta-data/",
"http://metadata.google.internal/computeMetadata/v1/",
"https://168.63.129.16/",
"https://224.0.0.1/",
"https://[64:ff9b::7f00:1]/",
"https://[::ffff:93.184.216.34]/",
],
)
def test_literal_local_and_metadata_targets_are_blocked(url) -> None:
with pytest.raises(UnsafeTarget):
SafeTargetGuard().resolve_url(url)
def test_dns_resolution_to_private_ip_is_blocked() -> None:
with pytest.raises(UnsafeTarget, match="non-public"):
guard_for("10.0.0.8").resolve_url("https://example.com/")
def test_adapter_pins_public_ip_and_preserves_tls_hostname() -> None:
adapter = PinnedDNSHTTPAdapter(guard_for(), max_retries=0)
captured = {}
class PoolManager:
def connection_from_host(self, **kwargs):
captured.update(kwargs)
return "pool"
adapter.poolmanager = PoolManager()
request = requests.Request("GET", "https://example.com/path").prepare()
assert adapter.get_connection_with_tls_context(request, True) == "pool"
assert captured["host"] == PUBLIC_IP
assert captured["pool_kwargs"]["server_hostname"] == "example.com"
assert captured["pool_kwargs"]["assert_hostname"] == "example.com"
assert request.headers["Host"] == "example.com"
def test_adapter_revalidates_and_blocks_an_unsafe_redirect_hop() -> None:
resolved_hosts = []
def resolver(host, _port):
resolved_hosts.append(host)
return [PUBLIC_IP if host == "example.com" else "127.0.0.1"]
adapter = PinnedDNSHTTPAdapter(SafeTargetGuard(resolver), max_retries=0)
class PoolManager:
def connection_from_host(self, **_kwargs):
return "pool"
adapter.poolmanager = PoolManager()
first = requests.Request("GET", "https://example.com/start").prepare()
redirect = requests.Request("GET", "https://internal.example/admin").prepare()
assert adapter.get_connection_with_tls_context(first, True) == "pool"
with pytest.raises(UnsafeTarget, match="non-public"):
adapter.get_connection_with_tls_context(redirect, True)
assert resolved_hosts == ["example.com", "internal.example"]
def test_checker_blocks_https_redirect_downgrade() -> None:
hop = FakeResponse(
302,
"https://example.com/start",
headers={"Location": "http://example.com/docs"},
)
session = FakeSession(hop)
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
result = checker.check_one(link())
assert result.status == "blocked"
assert "may not downgrade" in (result.error or "")
assert hop.closed is True
def test_thread_local_sessions_are_not_shared_between_workers() -> None:
created = []
barrier = threading.Barrier(2)
def factory():
value = object()
created.append(value)
return value
sessions = ThreadLocalSessions(factory)
results = []
def worker():
first = sessions.get()
barrier.wait()
results.append((first, sessions.get()))
threads = [threading.Thread(target=worker) for _ in range(2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert len(created) == 2
assert results[0][0] is results[0][1]
assert results[1][0] is results[1][1]
assert results[0][0] is not results[1][0]
def test_check_all_closes_worker_sessions() -> None:
sessions = []
def factory():
session = FakeSession(FakeResponse(200))
sessions.append(session)
return session
checker = LinkChecker(
guard=guard_for(), session_factory=factory, workers=1, min_interval=0
)
assert len(checker.check_all([link()])) == 1
assert len(sessions) == 1
assert sessions[0].closed is True
def test_mode_selects_internal_external_or_all() -> None:
data = {
"resources": [
{"id": "internal", "path": "foundations", "title": "I", "url": "/guide/"},
{
"id": "external",
"path": "foundations",
"title": "E",
"url": "https://docs.python.org/3/",
},
]
}
internal = select_links(data, mode="internal", base_url="https://flypython.com/")
external = select_links(data, mode="external", base_url="https://flypython.com/")
all_links = select_links(data, mode="all", base_url="https://flypython.com/")
assert [item.id for item in internal] == ["internal"]
assert [item.id for item in external] == ["external"]
assert len(all_links) == 2
def test_exit_code_fails_every_actionable_result() -> None:
for status in ("review", "broken", "blocked", "error"):
result = LinkResult("id", "path", "Title", "https://example.com", status)
report = build_report(catalog=Path("catalog.yml"), mode="all", results=[result])
assert exit_code_for_report(report) == 1
working = LinkResult(
"id", "path", "Title", "https://example.com", "working"
)
report = build_report(catalog=Path("catalog.yml"), mode="all", results=[working])
assert exit_code_for_report(report) == 0
@pytest.mark.parametrize(
"report",
[
{},
{"counts": {}},
{"counts": {"total": 0}},
{
"counts": {
"working": 1,
"redirect": 0,
"review": 0,
"broken": 0,
"blocked": 0,
"error": 0,
}
},
{
"counts": {
"working": 1,
"redirect": 0,
"review": 0,
"broken": 0,
"blocked": 0,
"error": 0,
"unknown": 1,
"total": 1,
}
},
{
"counts": {
"working": 0,
"redirect": 0,
"review": 0,
"broken": 0,
"blocked": 0,
"error": 0,
"total": 1,
}
},
],
)
def test_exit_code_rejects_malformed_reports(report: dict) -> None:
assert exit_code_for_report(report) == 2
def test_unknown_result_status_cannot_fail_open() -> None:
result = LinkResult("id", "path", "Title", "https://example.com", "typo")
report = build_report(catalog=Path("catalog.yml"), mode="all", results=[result])
assert exit_code_for_report(report) == 2
def test_unexpected_checker_error_is_fatal() -> None:
class BrokenSession(FakeSession):
def head(self, url, **kwargs):
raise RuntimeError("programming defect")
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: BrokenSession(FakeResponse(200)),
workers=1,
retries=0,
min_interval=0,
)
result = checker.check_one(link())
assert result.status == "error"
assert "programming defect" in (result.error or "")
@pytest.mark.parametrize(
"exception",
[
requests.exceptions.ConnectionError("connection failed"),
requests.exceptions.SSLError("certificate failed"),
requests.exceptions.TooManyRedirects("redirect loop"),
requests.exceptions.InvalidURL("invalid redirect"),
],
)
def test_terminal_request_failures_are_fatal(exception) -> None:
class BrokenSession(FakeSession):
def head(self, url, **kwargs):
raise exception
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: BrokenSession(FakeResponse(200)),
workers=1,
retries=0,
min_interval=0,
)
assert checker.check_one(link()).status == "error"
def test_timeout_remains_review_needed() -> None:
class SlowSession(FakeSession):
def head(self, url, **kwargs):
raise requests.Timeout("timed out")
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: SlowSession(FakeResponse(200)),
workers=1,
retries=0,
min_interval=0,
)
assert checker.check_one(link()).status == "review"
def test_adapter_transport_and_status_retries_are_disabled() -> None:
session = build_session(guard_for())
try:
retry = session.get_adapter("https://").max_retries
assert retry.respect_retry_after_header is False
assert retry.backoff_max == 5.0
assert retry.total == 0
assert retry.connect == 0
assert retry.read == 0
assert retry.status == 0
assert not retry.status_forcelist
finally:
session.close()
def test_status_retry_is_manual_and_closes_each_response() -> None:
first = FakeResponse(503)
second = FakeResponse(200)
class RetrySession(FakeSession):
def __init__(self):
super().__init__(first)
self.responses = iter([first, second])
def head(self, url, **kwargs):
self.calls.append(("HEAD", url, kwargs))
return next(self.responses)
session = RetrySession()
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: session,
workers=1,
retries=1,
backoff_factor=0,
min_interval=0,
)
result = checker.check_one(link())
assert result.status == "working"
assert len(session.calls) == 2
assert first.closed is True
assert second.closed is True
@pytest.mark.parametrize("retry_after", ["60", "9" * 400])
def test_large_retry_after_stops_without_get_fallback(
monkeypatch, retry_after: str
) -> None:
response = FakeResponse(429, headers={"Retry-After": retry_after})
session = FakeSession(response)
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: session,
workers=1,
retries=2,
min_interval=0,
)
sleeps = []
monkeypatch.setattr(check_links.time, "sleep", sleeps.append)
result = checker.check_one(link())
assert result.status == "review"
assert len(session.calls) == 1
assert sleeps == []
assert response.closed is True
def test_bounded_retry_after_is_honored(monkeypatch) -> None:
first = FakeResponse(429, headers={"Retry-After": "2"})
second = FakeResponse(200)
class RetrySession(FakeSession):
def __init__(self):
super().__init__(first)
self.responses = iter([first, second])
def head(self, url, **kwargs):
self.calls.append(("HEAD", url, kwargs))
return next(self.responses)
session = RetrySession()
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: session,
workers=1,
retries=1,
min_interval=0,
)
sleeps = []
monkeypatch.setattr(check_links.time, "sleep", sleeps.append)
result = checker.check_one(link())
assert result.status == "working"
assert len(session.calls) == 2
assert sleeps == [2.0]
def test_transport_timeout_retry_is_manual() -> None:
response = FakeResponse(200)
class FlakySession(FakeSession):
def __init__(self):
super().__init__(response)
self.attempt = 0
def head(self, url, **kwargs):
self.calls.append(("HEAD", url, kwargs))
self.attempt += 1
if self.attempt == 1:
raise requests.Timeout("timed out")
return response
session = FlakySession()
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: session,
workers=1,
retries=1,
backoff_factor=0,
min_interval=0,
)
result = checker.check_one(link())
assert result.status == "working"
assert len(session.calls) == 2
def test_wrapped_timeout_remains_review_needed() -> None:
class WrappedTimeoutSession(FakeSession):
def head(self, url, **kwargs):
raise requests.ConnectionError(TimeoutError("timed out"))
checker = LinkChecker(
guard=guard_for(),
session_factory=lambda: WrappedTimeoutSession(FakeResponse(200)),
workers=1,
retries=0,
min_interval=0,
)
assert checker.check_one(link()).status == "review"
def test_responses_close_when_result_processing_fails(monkeypatch) -> None:
head = FakeResponse(404)
response = FakeResponse(200)
session = FakeSession(head, response)
checker = LinkChecker(
guard=guard_for(), session_factory=lambda: session, workers=1, min_interval=0
)
def fail_classification(_status_code, *, redirected):
raise RuntimeError("cannot process response")
monkeypatch.setattr(check_links, "classify_status", fail_classification)
result = checker.check_one(link())
assert result.status == "error"
assert head.closed is True
assert response.closed is True
@pytest.mark.parametrize(
("option", "value"),
[
("--timeout", "nan"),
("--timeout", "inf"),
("--backoff", "nan"),
("--min-interval", "inf"),
],
)
def test_cli_rejects_non_finite_float_arguments(option: str, value: str) -> None:
with pytest.raises(SystemExit, match="2"):
check_links.build_parser().parse_args([option, value])
@pytest.mark.parametrize(
("status", "status_code", "expected_exit"),
[
("review", 408, 1),
("broken", 404, 1),
("blocked", None, 1),
("error", None, 1),
],
)
def test_cli_writes_json_and_uses_report_exit_code(
monkeypatch,
tmp_path: Path,
valid_catalog: dict,
status: str,
status_code: int | None,
expected_exit: int,
) -> None:
monkeypatch.setattr(check_links, "load_catalog", lambda _path: valid_catalog)
monkeypatch.setattr(check_links, "validate_catalog", lambda _data: [])
result = LinkResult(
"docs",
"foundations",
"Docs",
"https://example.com/docs",
status,
status_code=status_code,
method="GET" if status_code is not None else None,
)
monkeypatch.setattr(
check_links.LinkChecker, "check_all", lambda _self, _links: [result]
)
output = tmp_path / f"{status}.json"
exit_code = check_links.run(
["--catalog", "ignored.yml", "--output", str(output), "--min-interval", "0"]
)
assert exit_code == expected_exit
report = json.loads(output.read_text(encoding="utf-8"))
assert report["counts"][status] == 1
assert report["results"][0]["status_code"] == status_code