Download selftest.py from cormort/procurement-crawler-py: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/cormort/procurement-crawler-py/resolve/main/selftest.py
- Command line
-
hf download hf://spaces/cormort/procurement-crawler-py/selftest.py
-
curl -L -o selftest.py https://huggingface.co/spaces/cormort/procurement-crawler-py/resolve/main/selftest.py
14.8 kB
| """pcc_core 的離線自測(不需要網路、不需要 Streamlit)。 | |
| 跑法: | |
| python3 selftest.py # 離開碼 1 表示有案例失敗 | |
| 為什麼要這支:這個 Space 的核心風險是「對公開 API 的行為」——限速有沒有守住、 | |
| 被 429 之後會不會退避、非 JSON 回應會不會讓頁面整個掛掉、`columns[]` 帶回來的欄位有沒有被丟掉。 | |
| 這些都不需要真的打 API 就能驗(用假的 session / 假的時鐘),所以放在這裡當回歸測試。 | |
| """ | |
| import io | |
| import json | |
| import sys | |
| import requests | |
| from pcc_core import ( | |
| ApiError, | |
| LIST_COLUMNS, | |
| PccApi, | |
| RateLimiter, | |
| browser_headers, | |
| build_query_url, | |
| flatten_detail, | |
| human_like_delay, | |
| listing_rows, | |
| map_detail, | |
| official_request, | |
| parse_html_core, | |
| ) | |
| PASSED = 0 | |
| FAILED = 0 | |
| def check(name: str, condition: bool, detail: str = "") -> None: | |
| global PASSED, FAILED | |
| if condition: | |
| PASSED += 1 | |
| print(f"PASS {name}" + (f" [{detail}]" if detail else "")) | |
| else: | |
| FAILED += 1 | |
| print(f"FAIL {name}" + (f" [{detail}]" if detail else "")) | |
| # ---------- 假的 requests 物件 ---------- | |
| class FakeResponse: | |
| def __init__(self, status_code=200, payload=None, text="", headers=None): | |
| self.status_code = status_code | |
| self._payload = payload | |
| self.text = text if text else (json.dumps(payload) if payload is not None else "") | |
| self.headers = headers or ({"content-type": "application/json"} if payload is not None else {"content-type": "text/html"}) | |
| def json(self): | |
| if self._payload is None: | |
| raise json.JSONDecodeError("Expecting value", self.text or "", 0) | |
| return self._payload | |
| def raise_for_status(self): | |
| if self.status_code >= 400: | |
| error = requests.exceptions.HTTPError(f"HTTP {self.status_code}") | |
| error.response = self | |
| raise error | |
| class FakeSession: | |
| """記錄每一次請求,並依序回傳預先排好的回應。""" | |
| def __init__(self, responses): | |
| self.responses = list(responses) | |
| self.calls = [] | |
| def get(self, url, params=None, headers=None, timeout=None): | |
| self.calls.append({"url": url, "params": params, "headers": headers or {}}) | |
| if not self.responses: | |
| return FakeResponse(200, {"records": []}) | |
| item = self.responses.pop(0) | |
| if isinstance(item, Exception): | |
| raise item | |
| return item | |
| class FakeClock: | |
| def __init__(self): | |
| self.now = 1000.0 | |
| self.slept = [] | |
| def monotonic(self): | |
| return self.now | |
| def sleep(self, seconds): | |
| self.slept.append(seconds) | |
| self.now += seconds | |
| # ---------- 1. 限速器 ---------- | |
| def test_rate_limiter(): | |
| clock = FakeClock() | |
| limiter = RateLimiter(clock=clock.monotonic, sleep=clock.sleep, jitter=0) | |
| waits = [limiter.acquire() for _ in range(8)] | |
| check("限速器:前 8 次(10 秒窗口上限)不需等待", all(w == 0 for w in waits), f"等待 {waits}") | |
| ninth = limiter.acquire() | |
| check("限速器:第 9 次會等到 10 秒窗口清出空間", ninth > 0, f"等待 {ninth:.1f}s") | |
| # 長窗口:連續打 50 次後(10/60s 上限)應該開始受 60 秒窗口限制 | |
| clock2 = FakeClock() | |
| limiter2 = RateLimiter(clock=clock2.monotonic, sleep=clock2.sleep, jitter=0) | |
| total_wait = sum(limiter2.acquire() for _ in range(52)) | |
| check("限速器:60 秒窗口的上限(50 次)也會生效", total_wait > 0, f"52 次累計等待 {total_wait:.1f}s") | |
| check("限速器:不會超過最大窗口長度", limiter2.wait_time() <= 60.0, f"目前 wait_time={limiter2.wait_time():.1f}s") | |
| off = RateLimiter(enabled=False, clock=FakeClock().monotonic, sleep=lambda s: None) | |
| check("限速器:帶 Token 時停用(官方文件:Token 可解除流量限制)", | |
| all(off.acquire() == 0 for _ in range(50)) and off.wait_time() == 0) | |
| # ---------- 2. API 用戶端行為 ---------- | |
| def test_api_client(): | |
| # 2a. 429 → 退避後重試成功 | |
| clock = FakeClock() | |
| limiter = RateLimiter(clock=clock.monotonic, sleep=clock.sleep, jitter=0) | |
| session = FakeSession([FakeResponse(429), FakeResponse(200, {"records": [{"job_number": "A1"}]})]) | |
| api = PccApi(session=session, limiter=limiter) | |
| payload = api.get_json("tender", {"unit_id": "A", "job_number": "B"}) | |
| check("API:遇到 429 會冷卻重試並成功", payload.get("records") == [{"job_number": "A1"}], | |
| f"請求 {len(session.calls)} 次、冷卻等待 {clock.slept}") | |
| check("API:冷卻時間足夠讓 10 秒窗口清空", any(s >= 12 for s in clock.slept), f"sleep={clock.slept}") | |
| # 2b. 非 JSON 回應 → 明確錯誤(不是 JSONDecodeError 直接炸掉頁面) | |
| session = FakeSession([FakeResponse(200, payload=None, text="<html>blocked</html>")]) | |
| api = PccApi(session=session, limiter=RateLimiter(enabled=False)) | |
| try: | |
| api.get_json("searchbytitle", {"query": "x"}) | |
| check("API:非 JSON 回應會拋出 ApiError(不讓頁面崩潰)", False, "沒有拋錯") | |
| except ApiError as exc: | |
| check("API:非 JSON 回應會拋出 ApiError(不讓頁面崩潰)", "非 JSON" in str(exc), str(exc)[:60]) | |
| except Exception as exc: # noqa: BLE001 | |
| check("API:非 JSON 回應會拋出 ApiError(不讓頁面崩潰)", False, f"拋出 {type(exc).__name__}: {exc}") | |
| # 2c. 400 → 直接回報,不重試 | |
| session = FakeSession([FakeResponse(400, payload=None, text="bad")]) | |
| api = PccApi(session=session, limiter=RateLimiter(enabled=False)) | |
| try: | |
| api.get_json("tender", {"unit_id": "A"}) | |
| check("API:4xx 會立刻回報錯誤(不浪費重試)", False, "沒有拋錯") | |
| except ApiError as exc: | |
| check("API:4xx 會立刻回報錯誤(不浪費重試)", exc.status == 400, f"status={exc.status}") | |
| # 2d. 連線例外 → 重試後回報 | |
| session = FakeSession([requests.exceptions.ConnectionError("boom"), | |
| requests.exceptions.ConnectionError("boom"), | |
| requests.exceptions.ConnectionError("boom")]) | |
| api = PccApi(session=session, limiter=RateLimiter(enabled=False)) | |
| try: | |
| api.get_json("tender", {"unit_id": "A"}, max_retries=2) | |
| check("API:連線失敗會重試後回報錯誤", False, "沒有拋錯") | |
| except ApiError as exc: | |
| check("API:連線失敗會重試後回報錯誤", "連線失敗" in str(exc), str(exc)[:50]) | |
| # 2e. Token → 送 Authorization 且不限速 | |
| session = FakeSession([FakeResponse(200, {"ok": True})]) | |
| api = PccApi(token="hf_dummy", session=session) | |
| api.get_json("getinfo") | |
| check("API:帶 Token 會送 Authorization 標頭", | |
| session.calls[0]["headers"].get("Authorization") == "Bearer hf_dummy") | |
| check("API:帶 Token 時限速器自動停用", api.limiter.enabled is False) | |
| # 2e-2. 對外計數器(UI 會顯示;曾經因為少這個屬性讓整個頁面掛掉) | |
| clock = FakeClock() | |
| limiter = RateLimiter(clock=clock.monotonic, sleep=clock.sleep, jitter=0) | |
| session = FakeSession([FakeResponse(200, {"ok": 1}) for _ in range(12)]) | |
| api = PccApi(session=session, limiter=limiter) | |
| for _ in range(12): | |
| api.get_json("getinfo") | |
| check("API:requests_made 會累計(UI 顯示用)", api.requests_made == 12, f"requests_made={api.requests_made}") | |
| check("API:waited 會反映限速等待(UI 顯示用)", api.waited > 0, f"waited={api.waited:.1f}s") | |
| # 2f. columns[] 會被帶進查詢參數(一次請求取回詳細欄位) | |
| session = FakeSession([FakeResponse(200, {"records": []})]) | |
| api = PccApi(session=session, limiter=RateLimiter(enabled=False)) | |
| api.search_by_title("農田水利署", page=2, columns=LIST_COLUMNS) | |
| params = session.calls[0]["params"] | |
| column_params = [p for p in params if p[0] == "columns[]"] | |
| check("API:搜尋會帶上 columns[] 參數(N 次請求變 1 次)", | |
| len(column_params) == len(LIST_COLUMNS) and ("page", "2") in params, | |
| f"帶了 {len(column_params)} 個欄位") | |
| # ---------- 3. 欄位處理 ---------- | |
| def test_field_mapping(): | |
| detail = { | |
| "type": "招標公告", | |
| "url": "https://example.invalid/1", | |
| "pkPmsMain": "123", | |
| "fetched_at": "2026-01-01", | |
| "機關資料:機關名稱": "農田水利署", | |
| "採購資料:標案案號": "CN115010", | |
| "採購資料:標案名稱": "測試標案", | |
| "採購資料:預算金額": "38,630,000元", | |
| "領投開標:截止投標": "115/10/13 09:00", | |
| **{f"欄位{i}": f"值{i}" for i in range(80)}, | |
| } | |
| flat = flatten_detail(detail) | |
| check("欄位:flatten_detail 保留所有欄位(86 欄原樣帶出)", len(flat) == len(detail), f"{len(flat)}/{len(detail)}") | |
| flat_core = flatten_detail(detail, include_meta=False) | |
| check("欄位:include_meta=False 會濾掉 4 個 API 內部鍵", len(flat_core) == len(detail) - 4, | |
| f"{len(flat_core)} 欄") | |
| mapped = map_detail({ | |
| "type": "決標公告", | |
| "決標資料:決標公告日期": "115/02/01", | |
| "機關資料:單位名稱": "水利署", | |
| "決標資料:檔案案號": "CN115010", | |
| "決標資料:標案名稱": "測試標案", | |
| "決標資料:決標金額": "1,000,000元", | |
| "領投開標:開標時間": "115/02/02 10:00", | |
| }) | |
| check("欄位:map_detail 支援決標類公告的替代鍵名", | |
| mapped["機關名稱"] == "水利署" and mapped["預算/決標金額"] == "1,000,000元" | |
| and mapped["截止/開標日期"] == "115/02/02 10:00", | |
| json.dumps(mapped, ensure_ascii=False)[:80]) | |
| check("欄位:缺少的欄位回 N/A 而不是 None", | |
| map_detail({})["預算/決標金額"] == "N/A") | |
| records = [{ | |
| "job_number": "CN115010", "unit_id": "A.19.6", "unit_name": "農田水利署", "date": "20260101", | |
| "brief": {"type": "招標公告", "title": "測試標案"}, | |
| "detail": {"採購資料:預算金額": "38,630,000元", "領投開標:截止投標": "115/10/13 09:00"}, | |
| }] | |
| rows = listing_rows(records, "API", {"CN115010"}) | |
| check("列表:columns[] 帶回的預算/截止日會直接進列表(不必逐筆打 API)", | |
| rows[0]["預算/決標金額"] == "38,630,000元" and rows[0]["截止/開標日期"] == "115/10/13 09:00", | |
| json.dumps(rows[0], ensure_ascii=False)[:90]) | |
| check("列表:已爬過的案號會被標記且預設不勾選", | |
| rows[0]["狀態"] == "🚫 已爬過" and rows[0]["勾選"] is False) | |
| rows_fresh = listing_rows(records, "API", set()) | |
| check("列表:新案號預設勾選", rows_fresh[0]["勾選"] is True and rows_fresh[0]["狀態"] == "⭐ 新標案") | |
| # ---------- 4. 官網請求(防爬蟲與「只打一次」)---------- | |
| def test_official_site(): | |
| fixture = """ | |
| <html><body> | |
| <div class="title_1">招標公告</div> | |
| <table><tr><td>公告日</td><td>115/01/05</td></tr> | |
| <tr><td>機關名稱</td><td>農田水利署</td></tr> | |
| <tr><td>標案案號</td><td>CN115010</td></tr> | |
| <tr><td>標案名稱</td><td>測試標案</td></tr> | |
| <tr><td>預算金額</td><td>38,630,000元</td></tr> | |
| <tr><td>截止投標</td><td>115/10/13 09:00</td></tr></table> | |
| </body></html> | |
| """ | |
| parsed = parse_html_core(fixture) | |
| check("官網:parse_html_core 取得 7 個欄位", | |
| parsed["公告類型"] == "招標公告" and parsed["機關名稱"] == "農田水利署" | |
| and parsed["預算/決標金額"] == "38,630,000元" and parsed["截止/開標日期"] == "115/10/13 09:00", | |
| json.dumps(parsed, ensure_ascii=False)[:90]) | |
| session = FakeSession([FakeResponse(200, payload=None, text=fixture)]) | |
| html, status = official_request(session, "https://web.pcc.gov.tw/x", params={"a": "1"}) | |
| check("官網:official_request 一次請求就回傳 HTML(舊版同一次搜尋打兩次)", | |
| status == "OK" and html and len(session.calls) == 1, f"請求 {len(session.calls)} 次") | |
| session = FakeSession([FakeResponse(200, payload=None, text="請輸入驗證碼")]) | |
| html, status = official_request(session, "https://web.pcc.gov.tw/x") | |
| check("官網:偵測到驗證碼會回報 CAPTCHA", status == "CAPTCHA" and html is None) | |
| slept = [] | |
| session = FakeSession([FakeResponse(429, payload=None, text="too many"), FakeResponse(200, payload=None, text=fixture)]) | |
| html, status = official_request(session, "https://web.pcc.gov.tw/x", log=lambda m: None, sleep=slept.append) | |
| check("官網:429 會退避重試(不要硬打)", status == "OK" and any(s >= 60 for s in slept), f"sleep={slept}") | |
| check("官網:Headers 具備 Sec-Fetch-* 與 Referer", | |
| "Sec-Fetch-Mode" in browser_headers() and browser_headers("https://ref")["Referer"] == "https://ref") | |
| delay_min, delay_max, tail = 10 ** 9, 0, 0 | |
| for seed in range(400): | |
| import random as _random | |
| rng = _random.Random(seed) | |
| value = human_like_delay(3, 15, rng=rng) | |
| delay_min = min(delay_min, value) | |
| delay_max = max(delay_max, value) | |
| if value > 15: | |
| tail += 1 | |
| check("官網:延遲一定 ≥ 最小延遲且不超過 max+25(15% 尾巴)", | |
| delay_min >= 3 and delay_max <= 40, f"範圍 {delay_min:.1f}~{delay_max:.1f}s、尾巴 {tail}/400") | |
| check("官網:延遲尾巴確實存在(UI 必須揭露,否則時間估計會騙人)", tail > 0, f"{tail}/400 次超過 max_d") | |
| # ---------- 5. 其他 ---------- | |
| def test_misc(): | |
| url = build_query_url("https://web.pcc.gov.tw/prkms/tender/common/bulletion/readBulletion", | |
| {"querySentence": "農田水利署", "tenderStatusType": ["招標", "決標"], "pageSize": 20}) | |
| check("雜項:build_query_url 會跳過 list 值(狀態是另外帶的)", | |
| "querySentence=" in url and "tenderStatusType" not in url and "pageSize=20" in url, url[-60:]) | |
| from pcc_core import CANONICAL_ORDER | |
| check("雜項:標準欄位順序保留舊版欄位名(下游不用改)", | |
| CANONICAL_ORDER[:5] == ["公告類型", "公告日", "機關名稱", "標案案號", "標案名稱"]) | |
| def main() -> int: | |
| print("=== pcc_core 離線自測 ===") | |
| for test in (test_rate_limiter, test_api_client, test_field_mapping, test_official_site, test_misc): | |
| print(f"\n--- {test.__name__} ---") | |
| test() | |
| print(f"\n{PASSED} passed, {FAILED} failed") | |
| return 1 if FAILED else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |