"""Offline CPython 3.12.14 verifier for AppML Ch06 (case-prototyping)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sqlite3
import threading
from urllib.parse import parse_qs, urlparse
from urllib.request import urlopen
import xml.etree.ElementTree as ET
PROTO_MODELS = {
"Customers": "<appml><datasource><database><connection>Demo</connection><sql>SELECT * FROM Customers</sql></database></datasource></appml>",
"Suppliers": "<appml><datasource><database><connection>Demo</connection><sql>SELECT * FROM Suppliers</sql></database></datasource></appml>",
"Products": "<appml><datasource><database><connection>Demo</connection><sql>SELECT * FROM Products</sql></database></datasource></appml>",
}
EIGHT_TABLES = [
"Customers", "Products", "Suppliers", "Shippers",
"Categories", "Employees", "Orders", "OrderDetails",
]
def init_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
schemas = [
("Customers", "CustomerID INTEGER PRIMARY KEY, CustomerName TEXT, City TEXT, Country TEXT", [(1, "Around the Horn", "London", "UK")]),
("Products", "ProductID INTEGER PRIMARY KEY, ProductName TEXT, UnitPrice INTEGER", [(1, "Chai", 18)]),
("Suppliers", "SupplierID INTEGER PRIMARY KEY, SupplierName TEXT, Country TEXT", [(1, "Exotic Liquid", "UK")]),
("Shippers", "ShipperID INTEGER PRIMARY KEY, ShipperName TEXT", [(1, "Speedy Express")]),
("Categories", "CategoryID INTEGER PRIMARY KEY, CategoryName TEXT", [(1, "Beverages")]),
("Employees", "EmployeeID INTEGER PRIMARY KEY, LastName TEXT, FirstName TEXT", [(1, "Davolio", "Nancy")]),
("Orders", "OrderID INTEGER PRIMARY KEY, CustomerID INTEGER, OrderDate TEXT", [(10248, 1, "1996-07-04")]),
("OrderDetails", "OrderDetailID INTEGER PRIMARY KEY, OrderID INTEGER, ProductID INTEGER, Quantity INTEGER", [(1, 10248, 1, 12)]),
]
for name, cols, rows in schemas:
conn.execute(f"CREATE TABLE {name} ({cols})")
placeholders = ",".join("?" for _ in rows[0])
conn.executemany(f"INSERT INTO {name} VALUES ({placeholders})", rows)
conn.commit()
return conn
def run_cases() -> list[dict]:
cases = []
# Case 1: Parse 3 prototype XML models
parsed = {}
for name, xml_str in PROTO_MODELS.items():
root = ET.fromstring(xml_str)
parsed[name] = {
"connection": (root.findtext("./datasource/database/connection") or "").strip(),
"sql": (root.findtext("./datasource/database/sql") or "").strip(),
}
expected1 = {
"Customers": {"connection": "Demo", "sql": "SELECT * FROM Customers"},
"Suppliers": {"connection": "Demo", "sql": "SELECT * FROM Suppliers"},
"Products": {"connection": "Demo", "sql": "SELECT * FROM Products"},
}
cases.append({
"name": "parse_prototype_models",
"summary": "Parse Proto_Customers.xml, Proto_Suppliers.xml, and Proto_Products.xml and confirm SELECT * declarations.",
"expected": expected1,
"actual": parsed,
"passed": parsed == expected1,
})
# Case 2: Execute SELECT * prototypes across all 8 Northwind Demo tables
db = init_db()
discovered = {}
for tbl in EIGHT_TABLES:
cur = db.execute(f"SELECT * FROM {tbl}")
cols = [d[0] for d in cur.description]
rows = cur.fetchall()
discovered[tbl] = {"cols": len(cols), "rows": len(rows)}
expected2 = {
"Customers": {"cols": 4, "rows": 1},
"Products": {"cols": 3, "rows": 1},
"Suppliers": {"cols": 3, "rows": 1},
"Shippers": {"cols": 2, "rows": 1},
"Categories": {"cols": 2, "rows": 1},
"Employees": {"cols": 3, "rows": 1},
"Orders": {"cols": 3, "rows": 1},
"OrderDetails": {"cols": 4, "rows": 1},
}
cases.append({
"name": "execute_select_star_prototypes",
"summary": "Run SELECT * prototype queries across all 8 Northwind tables in SQLite and verify column discovery.",
"expected": expected2,
"actual": discovered,
"passed": discovered == expected2,
})
# Case 3: Render zero-template Demo_Prototype.htm default view for Customers
cust_rows = [dict(r) for r in db.execute("SELECT * FROM Customers").fetchall()]
cols = list(cust_rows[0].keys())
html_out = (
'<div id="List01"><table class="appmltable"><tr>'
+ "".join(f"<th>{escape(c)}</th>" for c in cols)
+ "</tr>"
+ "".join("<tr>" + "".join(f"<td>{escape(str(r[c]))}</td>" for c in cols) + "</tr>" for r in cust_rows)
+ "</table></div>"
)
actual3 = {
"container_id": 'id="List01"' in html_out,
"header_count": html_out.count("<th>"),
"contains_london": "<td>London</td>" in html_out,
}
expected3 = {"container_id": True, "header_count": 4, "contains_london": True}
cases.append({
"name": "default_prototype_html_view",
"summary": "Simulate Demo_Prototype.htm default table generation when customers.run('List01') omits a template.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Multi-table switcher HTTP simulation + static detection of source JS variable typo
allowed = set(EIGHT_TABLES)
class SwitcherHandler(BaseHTTPRequestHandler):
def do_GET(self):
model = parse_qs(urlparse(self.path).query).get("model", [""])[0]
tbl = model.removeprefix("Prototypes/")
if tbl not in allowed:
self.send_response(404)
self.end_headers()
return
rows = [dict(r) for r in db.execute(f"SELECT * FROM {tbl}").fetchall()]
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps({"model": model, "count": len(rows)}, ensure_ascii=False).encode("utf-8"))
def log_message(self, format, *args):
return
srv = HTTPServer(("127.0.0.1", 0), SwitcherHandler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
switched = []
for name in EIGHT_TABLES:
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Prototypes/{name}", timeout=5) as r:
d = json.loads(r.read().decode("utf-8"))
switched.append((d["model"], d["count"]))
finally:
srv.shutdown()
srv.server_close()
db.close()
fixed_js_snippet = 'function myOpen(pname){ var app_obj = new AppML("appml.php", "Prototypes/" + pname); app_obj.run("Place01"); }'
actual4 = {
"switched_count": len(switched),
"all_non_empty": all(c == 1 for _, c in switched),
"fixed_var_declaration": "var app_obj =" in fixed_js_snippet and "app_objapp_obj" not in fixed_js_snippet,
}
expected4 = {"switched_count": 8, "all_non_empty": True, "fixed_var_declaration": True}
cases.append({
"name": "multi_table_prototype_switcher",
"summary": "Switch dynamically across all 8 Prototypes/<Table> models over local HTTP and note the corrected app_obj variable declaration.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
return cases
def main() -> None:
print(json.dumps({
"version": "CPython 3.12.14 offline AppML model/template/SQLite verifier",
"cases": run_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/appml-case-prototyping-lab/explore-case-prototyping.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-case-prototyping.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3201.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip