蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 SisterApi JSON 分页解析与 AsyncTask 生命周期取消防泄漏核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-exercise-2.py
explore-tutorial-exercise-2.py174 行
"""Offline Android capstone verifier for Ch 152: DrySister Part 2 (JSON Parsing & AsyncTask Fix)."""
from dataclasses import dataclass
import json


VERSION = (
    "CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
    "(Android SDK/emulator absent)"
)

SAMPLE_API_JSON = json.dumps(
    {
        "error": False,
        "results": [
            {
                "_id": "57a55f1d421aa9125a34e001",
                "createdAt": "2016-08-06T09:10:00.000Z",
                "desc": "8-6",
                "publishedAt": "2016-08-06T12:00:00.000Z",
                "source": "chrome",
                "type": "福利",
                "url": "https://example.invalid/p1_01.jpg",
                "used": True,
                "who": "daimajia",
            },
            {
                "_id": "57a55f1d421aa9125a34e002",
                "createdAt": "2016-08-05T09:10:00.000Z",
                "desc": "8-5",
                "publishedAt": "2016-08-05T12:00:00.000Z",
                "source": "chrome",
                "type": "福利",
                "url": "https://example.invalid/p1_02.jpg",
                "used": True,
                "who": "daimajia",
            },
        ],
    },
    ensure_ascii=False,
)


@dataclass
class Sister:
    _id: str
    create_at: str
    desc: str
    published_at: str
    source: str
    item_type: str
    url: str
    used: bool
    who: str


def parse_sister_json(content: str) -> list[Sister]:
    payload = json.loads(content)
    items = []
    for rec in payload["results"]:
        items.append(
            Sister(
                _id=rec["_id"],
                create_at=rec["createdAt"],
                desc=rec["desc"],
                published_at=rec["publishedAt"],
                source=rec["source"],
                item_type=rec["type"],
                url=rec["url"],
                used=bool(rec["used"]),
                who=rec["who"],
            )
        )
    return items


class SisterTaskModel:
    def __init__(self, page: int) -> None:
        self.page = page
        self.cancelled = False

    def cancel(self, may_interrupt: bool) -> bool:
        self.cancelled = True
        return may_interrupt


def main() -> None:
    # Case 1: SisterApi JSON list parsing & URL pagination template
    sisters = parse_sister_json(SAMPLE_API_JSON)
    page1_url = f"http://gank.io/api/data/福利/{10}/{1}"
    page2_url = f"http://gank.io/api/data/福利/{10}/{2}"
    c1_actual = {
        "parsed_count": len(sisters),
        "first_id": sisters[0]._id,
        "first_created_at": sisters[0].create_at,
        "first_used": sisters[0].used,
        "urls": [s.url for s in sisters],
        "pagination_endpoints": [page1_url, page2_url],
    }
    c1_expected = {
        "parsed_count": 2,
        "first_id": "57a55f1d421aa9125a34e001",
        "first_created_at": "2016-08-06T09:10:00.000Z",
        "first_used": True,
        "urls": ["https://example.invalid/p1_01.jpg", "https://example.invalid/p1_02.jpg"],
        "pagination_endpoints": [
            "http://gank.io/api/data/福利/10/1",
            "http://gank.io/api/data/福利/10/2",
        ],
    }

    # Case 2: MainActivity pagination & AsyncTask onDestroy cancel + null-safety fix
    data: list[Sister] = []
    page = 1
    cur_pos = 0
    sister_task: SisterTaskModel | None = None

    # Safe onDestroy when user exits before ever clicking refresh (sister_task is None)
    npe_avoided_when_null = True
    if sister_task is not None:
        sister_task.cancel(True)

    # Refresh page 1
    sister_task = SisterTaskModel(page)
    data.clear()
    data.extend(sisters)
    page += 1
    cur_pos = 0
    shown_1 = data[cur_pos].url
    cur_pos += 1
    shown_2 = data[cur_pos].url

    # Cancel active task in onDestroy -> onCancelled clears reference
    cancelled_in_destroy = False
    if sister_task is not None:
        cancelled_in_destroy = sister_task.cancel(True)
        sister_task = None  # simulates onCancelled()

    c2_actual = {
        "npe_avoided_when_task_null": npe_avoided_when_null,
        "shown_urls": [shown_1, shown_2],
        "page_after_post_execute": page,
        "cancelled_in_on_destroy": cancelled_in_destroy,
        "task_ref_cleared_after_cancel": sister_task is None,
    }
    c2_expected = {
        "npe_avoided_when_task_null": True,
        "shown_urls": ["https://example.invalid/p1_01.jpg", "https://example.invalid/p1_02.jpg"],
        "page_after_post_execute": 2,
        "cancelled_in_on_destroy": True,
        "task_ref_cleared_after_cancel": True,
    }

    cases = [
        {
            "name": "sister_json_pagination_parsing",
            "summary": "验证 Sister 9 字段模型与 SisterApi 对 JSON results 数组的分页解析",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "asynctask_lifecycle_leak_fix_and_pagination",
            "summary": "验证分页游标推进、onDestroy 取消 AsyncTask 与判空防 NPE 内存泄漏修复逻辑",
            "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-2-lab/explore-tutorial-exercise-2.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-exercise-2.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1880.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习