# -*- coding: utf-8 -*- """sec-ch-ua 系列请求头:为什么必须带、怎么还原。 抖音网关对「声称自己是 Chrome、却没带 sec-ch-ua」的请求会回 **200 + 空 body** —— 不报错、不给原因、HTTP 状态还是成功的,采集侧只看到 0 条。实测同一 URL、同一 cookie、 同一参数:不带头 0 字节,补上这三个头 7077 字节。 """ import pytest from media_platform.douyin.help import client_hint_headers # 实测从真实浏览器抓到的 navigator.userAgentData REAL_UA_DATA = { "brands": [ {"brand": "Google Chrome", "version": "155"}, {"brand": "Chromium", "version": "155"}, {"brand": "Not(A:Brand", "version": "24"}, ], "mobile": False, "platform": "Linux", } def test_headers_are_derived_from_user_agent_data(): hints = client_hint_headers(REAL_UA_DATA) assert hints["sec-ch-ua"] == ( '"Google Chrome";v="155", "Chromium";v="155", "Not(A:Brand";v="24"' ) assert hints["sec-ch-ua-mobile"] == "?0" assert hints["sec-ch-ua-platform"] == '"Linux"' def test_mobile_is_reflected(): hints = client_hint_headers({**REAL_UA_DATA, "mobile": True}) assert hints["sec-ch-ua-mobile"] == "?1" @pytest.mark.parametrize("value", [None, [], "not-a-dict", {}, {"brands": []}]) def test_nothing_is_invented_when_user_agent_data_is_unavailable(value): """拿不到就返回空。 凭空造一组和 UA 对不上的头,只会变成**另一个**可疑特征 —— 那比不带头更糟。 """ assert client_hint_headers(value) == {} def test_missing_platform_still_sends_the_other_two(): hints = client_hint_headers({"brands": REAL_UA_DATA["brands"], "mobile": False}) assert "sec-ch-ua" in hints assert "sec-ch-ua-mobile" in hints assert "sec-ch-ua-platform" not in hints