写一段 pytest 代码,验证所有内部链接返回 200 且外部链接允许 302
解读
国内技术文档站点普遍采用“静态站点生成器 + CI/CD”模式,文档上线前要在测试环境跑自动化检查。面试官想确认三件事:
- 能否把“内部/外部”定义清楚(通常用域名白名单或正则)
- 能否用 pytest 组织用例,做到“失败即阻断、报告可读”
- 是否理解国内网络真实状况:外部链偶尔 302 到 CDN、广告页或微信登录页,不能粗暴判 200;内部链一旦出现 301/404 则必须拦截,否则影响 SEO 与用户体验
因此,代码要同时满足“可维护、可扩展、可集成到 GitLab-CI/GitHub Actions”三条硬指标,而不是写个一次性脚本。
知识点
- pytest 参数化与 fixture:用
@pytest.mark.parametrize一次性生成千级链接用例,失败用例独立展示 - 请求层:使用
requests库,设置allow_redirects=False先抓首包状态码,再对 302 做二次跟踪,避免把 302→200 误判成 200 - 域名白名单:通过配置
INTERNAL_DOMAINS = {"docs.example.com", "api.example.com"}判断内外链,方便后续加微服务子域 - 重试与超时:国内出口带宽抖动,需加
urllib3.util.retry.Retry与timeout=10,防止 CI 偶发失败 - 并发加速:用
pytest-xdist或asyncio+aiohttp均可,但面试场景以“可读性”优先,示范用同步即可 - 断言粒度:内部链
assert r.status_code == 200;外部链assert r.status_code in (200, 302),并在失败详情里打印location头,方便肉眼复核 - 安全合规:CI 变量里放
DOCS_BASIC_AUTH,防止测试环境被搜索引擎爬虫误抓;代码里强制headers = {"User-Agent": "DocsLinkBot/1.0 (CI check)"}
答案
项目结构(最小可运行):
tests/
├── conftest.py
└── test_links.py
conftest.py
import pytest
import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
# 内部域名白名单,可随环境变量注入
INTERNAL_DOMAINS = {"docs.example.com", "api.example.com"}
# 统一 session,带重试
@pytest.fixture(scope="session")
def session():
sess = requests.Session()
retries = Retry(total=3, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504])
sess.mount("http://", HTTPAdapter(max_retries=retries))
sess.mount("https://", HTTPAdapter(max_retries=retries))
sess.headers.update({"User-Agent": "DocsLinkBot/1.0 (CI check)"})
return sess
test_links.py
import pytest
import requests
from conftest import INTERNAL_DOMAINS
def _is_internal(url: str) -> bool:
from urllib.parse import urlparse
return urlparse(url).netloc in INTERNAL_DOMAINS
def collect_links():
"""
实际项目中这里可以:
1. 解析 sitemap.xml
2. 调用 sphinx/mkdocs 插件吐出的 link.json
3. 扫 HTML 文件夹
为了面试 demo,直接写死
"""
return [
"https://docs.example.com/guide/quickstart",
"https://docs.example.com/api/auth",
"https://github.com/example/docs", # 外部
"https://www.ietf.org/rfc/rfc2616.txt" # 外部
]
@pytest.mark.parametrize("url", collect_links())
def test_link_status(url, session):
resp = session.get(url, allow_redirects=False, timeout=10)
if _is_internal(url):
assert resp.status_code == 200, f"Internal link {url} returned {resp.status_code}"
else:
# 外部链允许 200 或 302;如果是 302,把 location 打印出来方便复核
assert resp.status_code in (200, 302), \
f"External link {url} returned {resp.status_code}, location={resp.headers.get('Location')}"
运行:
pip install pytest requests
pytest -q --tb=short
输出示例:
.... [100%]
4 passed in 2.31s
若内部链 404,会精准定位到具体 URL,符合国内企业对“上线门禁”的硬性要求。
拓展思考
- 增量检测:在 MR 阶段只检查“新增或变更的 md/html 文件”,用
git diff --name-only过滤,节省流水线时间 - 多语言镜像:国内站点常同时部署
.com与.cn域名,可在白名单加docs.example.cn,并断言.cn必须备案号齐全 - 登录态链路:部分内部链需要 JWT,可在 fixture 里先调
/login接口拿 token,再注入Authorization头 - 报告可视化:接入
pytest-html或allure,把失败截图、响应头、重定向链一并输出,方便文档团队直接点击复查 - 定时巡检:把同一份代码放到 nightly job,结合 Prometheus exporter 把“404 数量”当指标,实现“技术文档 SLO”可观测