"""Offline Android capstone verifier for Ch 155: DrySister Part 5 (AS 3.0 Migration, LogUtils & CrashHandler)."""
import json
from pathlib import Path
import tempfile
from urllib.parse import quote
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
LOG_LEVELS = {"V": 2, "D": 3, "I": 4, "W": 5, "E": 6}
class StructuredLogger:
"""Models Android LogUtils gated by BuildConfig.DEBUG and minimum log level."""
def __init__(self, build_config_debug: bool, min_level: str = "V") -> None:
self.debug_enabled = build_config_debug
self.min_rank = LOG_LEVELS[min_level]
self.records: list[dict] = []
def log(self, level: str, tag: str, message: str) -> bool:
rank = LOG_LEVELS[level]
# In release builds (BuildConfig.DEBUG == False), suppress debug/verbose logs;
# full LogUtils gate suppresses all debug output when debug_enabled is False.
if not self.debug_enabled:
return False
if rank < self.min_rank:
return False
self.records.append({"level": level, "tag": tag, "message": message})
return True
def build_crash_report(
timestamp_str: str,
device_info: dict[str, str],
exc_type: str,
exc_msg: str,
) -> str:
lines = [f"crash_time={timestamp_str}"]
for k in sorted(device_info):
lines.append(f"{k}={device_info[k]}")
lines.append(f"exception={exc_type}: {exc_msg}")
return "\n".join(lines) + "\n"
def main() -> None:
# Case 1: AS 3.0 migration — Chinese URL segment percent-encoding & rebase commit linearity
base_prefix = "http://gank.io/api/data/"
encoded_segment = quote("福利", encoding="utf-8").lower()
encoded_full_url = f"{base_prefix}{encoded_segment}/10/1"
# Verify naive full-URL encoding corrupts scheme "://"
corrupted_full_url = quote(f"{base_prefix}福利/10/1", safe="", encoding="utf-8")
# Simulate git rebase: feature commits replayed linearly onto develop tip
develop_commits = ["c1_init", "c2_json", "c3_cache", "c4_db"]
feature_commits = ["f1_as3_gradle", "f2_log_crash"]
rebased_history = develop_commits + feature_commits
c1_actual = {
"encoded_segment": encoded_segment,
"valid_api_url": encoded_full_url,
"naive_full_encode_breaks_scheme": not corrupted_full_url.startswith("http://"),
"rebased_linear_count": len(rebased_history),
"rebased_head": rebased_history[-1],
}
c1_expected = {
"encoded_segment": "%e7%a6%8f%e5%88%a9",
"valid_api_url": "http://gank.io/api/data/%e7%a6%8f%e5%88%a9/10/1",
"naive_full_encode_breaks_scheme": True,
"rebased_linear_count": 6,
"rebased_head": "f2_log_crash",
}
# Case 2: Log level filter (V/D/I/W/E) + BuildConfig.DEBUG guard + CrashHandler file persistence
events = [
("V", "SisterApi", "raw response stream"),
("D", "SisterLoader", "cache lookup key"),
("I", "MainActivity", "page 2 loaded"),
("W", "DiskCache", "near max capacity"),
("E", "Network", "HTTP 500 error"),
]
debug_logger_all = StructuredLogger(build_config_debug=True, min_level="V")
debug_logger_info = StructuredLogger(build_config_debug=True, min_level="I")
release_logger = StructuredLogger(build_config_debug=False, min_level="V")
for lvl, tag, msg in events:
debug_logger_all.log(lvl, tag, msg)
debug_logger_info.log(lvl, tag, msg)
release_logger.log(lvl, tag, msg)
# CrashHandler: catch ZeroDivisionError (1/0), write report to temp Crash/ directory
with tempfile.TemporaryDirectory() as tmp:
crash_dir = Path(tmp) / "Crash"
crash_dir.mkdir(parents=True, exist_ok=True)
try:
_ = 1 // 0
except ZeroDivisionError as exc:
report = build_crash_report(
timestamp_str="2017-12-22_14-30-00",
device_info={"versionName": "1.0.0", "versionCode": "1", "MODEL": "Meilan_E2", "SDK_INT": "26"},
exc_type=type(exc).__name__,
exc_msg=str(exc),
)
crash_file = crash_dir / "crash-2017-12-22_14-30-00.log"
crash_file.write_text(report, encoding="utf-8")
written_lines = crash_file.read_text(encoding="utf-8").strip().splitlines()
c2_actual = {
"debug_all_levels": [r["level"] for r in debug_logger_all.records],
"debug_min_info_levels": [r["level"] for r in debug_logger_info.records],
"release_emitted_count": len(release_logger.records),
"crash_report_line_count": len(written_lines),
"crash_report_has_exception": any("ZeroDivisionError" in ln for ln in written_lines),
}
c2_expected = {
"debug_all_levels": ["V", "D", "I", "W", "E"],
"debug_min_info_levels": ["I", "W", "E"],
"release_emitted_count": 0,
"crash_report_line_count": 6,
"crash_report_has_exception": True,
}
cases = [
{
"name": "as3_url_encoding_and_git_rebase",
"summary": "验证中文路径分段 UTF-8 百分号转码(避免破坏协议头)及 git rebase 线性提交历史",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "logutils_level_filter_and_crashhandler",
"summary": "验证 V/D/I/W/E 五级日志过滤、BuildConfig.DEBUG 开关门控及 CrashHandler 异常落盘采集",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-exercise-5-lab/explore-tutorial-exercise-5.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-exercise-5.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1883.zip