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

运行真实 sqlite3 引擎验证 SisterOpenHelper 建表、事务回滚、分页与首行漏读缺陷

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-exercise-4.py
explore-tutorial-exercise-4.py212 行
"""Offline Android capstone verifier for Ch 154: DrySister Part 4 (Real SQLite3 Offline Cache)."""
import json
import sqlite3
import xml.etree.ElementTree as ET


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

CREATE_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS fuli (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    _id TEXT,
    createAt TEXT,
    desc TEXT,
    publishedAt TEXT,
    source TEXT,
    type TEXT,
    url TEXT,
    used BOOLEAN,
    who TEXT
)
"""

LAYOUT_XML = """<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/btn_previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:visibility="invisible"
        android:text="上一个"/>
    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@id/btn_previous"
        android:text="下一个"/>
    <ImageView
        android:id="@+id/img_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_previous"/>
</RelativeLayout>
"""


def make_rows(start: int, count: int) -> list[tuple]:
    return [
        (
            f"id_{i:03d}",
            f"2016-08-{i:02d}T09:00:00Z",
            f"desc_{i}",
            f"2016-08-{i:02d}T12:00:00Z",
            "chrome",
            "福利",
            f"https://example.invalid/s_{i:03d}.jpg",
            1,
            "editor",
        )
        for i in range(start, start + count)
    ]


def main() -> None:
    conn = sqlite3.connect(":memory:")
    cur = conn.cursor()
    cur.execute(CREATE_TABLE_SQL)
    conn.commit()

    # Case 1: SisterOpenHelper schema creation, transactional batch insert & rollback safety
    cols = [row[1] for row in cur.execute("PRAGMA table_info(fuli)").fetchall()]
    page1 = make_rows(1, 10)
    page2 = make_rows(11, 10)

    # Atomic batch insert for page 1 + page 2
    with conn:
        cur.executemany(
            "INSERT INTO fuli (_id, createAt, desc, publishedAt, source, type, url, used, who) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            page1 + page2,
        )
    count_after_batch = cur.execute("SELECT COUNT(*) FROM fuli").fetchone()[0]

    # Simulate failed transaction rollback (must keep count=20)
    try:
        conn.execute("BEGIN")
        conn.execute(
            "INSERT INTO fuli (_id, createAt, desc, publishedAt, source, type, url, used, who) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            make_rows(21, 1)[0],
        )
        raise RuntimeError("simulated mid-transaction failure")
    except RuntimeError:
        conn.rollback()
    count_after_rollback = cur.execute("SELECT COUNT(*) FROM fuli").fetchone()[0]

    c1_actual = {
        "schema_columns": cols,
        "count_after_2_page_tx": count_after_batch,
        "count_after_rollback": count_after_rollback,
    }
    c1_expected = {
        "schema_columns": [
            "id", "_id", "createAt", "desc", "publishedAt", "source", "type", "url", "used", "who"
        ],
        "count_after_2_page_tx": 20,
        "count_after_rollback": 20,
    }

    # Case 2: CRUD (update/delete), LIMIT offset,count pagination & moveToFirst()+moveToNext() bug proof
    cur.execute("UPDATE fuli SET desc = ? WHERE _id = ?", ("updated_desc_001", "id_001"))
    conn.commit()
    updated_desc = cur.execute("SELECT desc FROM fuli WHERE _id = ?", ("id_001",)).fetchone()[0]

    # Pagination: curPage=1 (0-based), limit=10 -> LIMIT 10, 10 (SQLite supports LIMIT offset, count)
    p1_ids = [r[0] for r in cur.execute("SELECT _id FROM fuli ORDER BY id LIMIT 0, 10").fetchall()]
    p2_ids = [r[0] for r in cur.execute("SELECT _id FROM fuli ORDER BY id LIMIT 10, 10").fetchall()]

    # Demonstrate source bug in getAllSisters(): calling moveToFirst() then while(moveToNext()) skips row 0!
    all_rows = cur.execute("SELECT _id FROM fuli ORDER BY id").fetchall()
    buggy_cursor_count = len(all_rows[1:])  # skips index 0
    fixed_cursor_count = len(all_rows)

    cur.execute("DELETE FROM fuli WHERE _id = ?", ("id_020",))
    conn.commit()
    count_after_delete = cur.execute("SELECT COUNT(*) FROM fuli").fetchone()[0]

    c2_actual = {
        "updated_desc": updated_desc,
        "page0_first_last": [p1_ids[0], p1_ids[-1]],
        "page1_first_last": [p2_ids[0], p2_ids[-1]],
        "buggy_moveToFirst_then_moveToNext_skips_row0": buggy_cursor_count,
        "fixed_while_moveToNext_count": fixed_cursor_count,
        "count_after_delete_one": count_after_delete,
    }
    c2_expected = {
        "updated_desc": "updated_desc_001",
        "page0_first_last": ["id_001", "id_010"],
        "page1_first_last": ["id_011", "id_020"],
        "buggy_moveToFirst_then_moveToNext_skips_row0": 19,
        "fixed_while_moveToNext_count": 20,
        "count_after_delete_one": 19,
    }

    # Case 3: Online dedup guard, offline fallback & RelativeLayout Previous/Next XML check
    root = ET.fromstring(LAYOUT_XML)
    ns = "{http://schemas.android.com/apk/res/android}"
    btn_prev = root.findall("Button")[0]
    initial_prev_vis = btn_prev.attrib[f"{ns}visibility"]

    # Dedup guard: getSistersCount() // 10 < page
    should_insert_page1_when_db_has_0 = (0 // 10) < 1
    should_insert_page1_when_db_has_10 = (10 // 10) < 1
    should_insert_page2_when_db_has_10 = (10 // 10) < 2

    # Offline fallback fetches page 1 (offset 0, limit 10) directly from SQLite
    offline_urls = [r[0] for r in cur.execute("SELECT url FROM fuli ORDER BY id LIMIT 0, 10").fetchall()]
    conn.close()

    c3_actual = {
        "initial_prev_button_visibility": initial_prev_vis,
        "dedup_guard_matrix": [
            should_insert_page1_when_db_has_0,
            should_insert_page1_when_db_has_10,
            should_insert_page2_when_db_has_10,
        ],
        "offline_page1_count": len(offline_urls),
        "offline_first_url": offline_urls[0],
    }
    c3_expected = {
        "initial_prev_button_visibility": "invisible",
        "dedup_guard_matrix": [True, False, True],
        "offline_page1_count": 10,
        "offline_first_url": "https://example.invalid/s_001.jpg",
    }

    cases = [
        {
            "name": "sqlite_schema_and_transaction_batch",
            "summary": "使用真实 sqlite3 引擎验证 SisterOpenHelper 建表 10 列结构、事务批量插入与异常回滚原子性",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "sqlite_crud_pagination_and_cursor_bug",
            "summary": "验证 SQLite 更新/删除/LIMIT 分页查询,并复现 moveToFirst()+moveToNext() 漏读首行缺陷",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "online_dedup_offline_fallback_and_layout",
            "summary": "验证断网回落本地数据库读取、防重复插入条件判断及上/下一页布局按钮初始可见性",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_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-4-lab/explore-tutorial-exercise-4.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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