"""Offline MongoDB Shell (mongosh) CLI, session & CRUD walkthrough verifier (Ch07 shell)."""
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def parse_mongosh_args(argv):
host = "127.0.0.1"
port = 27017
show_version = False
i = 0
while i < len(argv):
if argv[i] == "--version":
show_version = True
elif argv[i] == "--host" and i + 1 < len(argv):
val = argv[i + 1]
if ":" in val:
host, p = val.rsplit(":", 1)
port = int(p)
else:
host = val
i += 1
elif argv[i] == "--port" and i + 1 < len(argv):
port = int(argv[i + 1])
i += 1
i += 1
return {"host": host, "port": port, "show_version": show_version}
def case_mongosh_cross_platform_install_spec():
install_targets = {
"macos_manual": ["/usr/local/bin/mongosh", "/usr/local/lib/mongosh_crypt_v1.so"],
"linux_apt": "/etc/apt/sources.list.d/mongodb-org-7.0.list",
"windows_msi": "mongosh.exe",
}
actual = {
"platforms_covered": len(install_targets),
"crypt_lib_included": any("mongosh_crypt_v1.so" in p for p in install_targets["macos_manual"]),
"apt_list_suffix_ok": install_targets["linux_apt"].endswith(".list"),
}
expected = {
"platforms_covered": 3,
"crypt_lib_included": True,
"apt_list_suffix_ok": True,
}
return {
"name": "mongosh_cross_platform_install_spec",
"summary": "核对 macOS、Linux 与 Windows 平台安装 mongosh 的二进制路径与加密库配置规范。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mongosh_cli_connection_parser():
default_conn = parse_mongosh_args([])
remote_conn = parse_mongosh_args(["--host", "db.example.internal:27018"])
ver_flag = parse_mongosh_args(["--version"])
actual = {
"default_host_port": [default_conn["host"], default_conn["port"]],
"remote_host_port": [remote_conn["host"], remote_conn["port"]],
"version_flag": ver_flag["show_version"],
}
expected = {
"default_host_port": ["127.0.0.1", 27017],
"remote_host_port": ["db.example.internal", 27018],
"version_flag": True,
}
return {
"name": "mongosh_cli_connection_parser",
"summary": "解析 mongosh 默认连接 127.0.0.1:27017、--host <host>:<port> 与 --version 命令行参数。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mongosh_session_commands():
dbs = {"admin": {}, "config": {}, "local": {}, "demo": {"items": []}}
cur = "test"
initial_db = cur
listed = sorted(dbs.keys())
cur = "demo"
switched_db = cur
exit_aliases = {"quit()", "exit"}
actual = {
"initial_db": initial_db,
"show_dbs": listed,
"switched_db": switched_db,
"exit_commands_valid": "quit()" in exit_aliases and "exit" in exit_aliases,
}
expected = {
"initial_db": "test",
"show_dbs": ["admin", "config", "demo", "local"],
"switched_db": "demo",
"exit_commands_valid": True,
}
return {
"name": "mongosh_session_commands",
"summary": "验证 db、show dbs、use <db> 以及 quit()/exit 会话控制命令状态转移。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mongosh_full_crud_walkthrough():
coll = []
oid = "667cd8789a69705686ed70f2"
# insertOne
doc = {"_id": oid, "name": "Alice", "age": 30}
coll.append(doc)
ins_res = {"acknowledged": True, "insertedId": oid}
# find
found_before = [dict(d) for d in coll]
# updateOne({name: "Alice"}, {$set: {age: 31}})
matched = modified = 0
for d in coll:
if d["name"] == "Alice":
matched += 1
if d["age"] != 31:
d["age"] = 31
modified += 1
break
upd_res = {
"acknowledged": True,
"insertedId": None,
"matchedCount": matched,
"modifiedCount": modified,
"upsertedCount": 0,
}
age_after_update = coll[0]["age"]
# deleteOne({name: "Alice"})
deleted = 0
for i, d in enumerate(coll):
if d["name"] == "Alice":
coll.pop(i)
deleted = 1
break
del_res = {"acknowledged": True, "deletedCount": deleted}
actual = {
"insert_ok": ins_res["acknowledged"] and bool(re.fullmatch(r"[0-9a-f]{24}", ins_res["insertedId"])),
"found_before_age": found_before[0]["age"],
"update_res": upd_res,
"age_after_update": age_after_update,
"delete_res": del_res,
"remaining_docs": len(coll),
}
expected = {
"insert_ok": True,
"found_before_age": 30,
"update_res": {
"acknowledged": True,
"insertedId": None,
"matchedCount": 1,
"modifiedCount": 1,
"upsertedCount": 0,
},
"age_after_update": 31,
"delete_res": {"acknowledged": True, "deletedCount": 1},
"remaining_docs": 0,
}
return {
"name": "mongosh_full_crud_walkthrough",
"summary": "完整执行 insertOne -> find -> updateOne -> deleteOne 交互流程并核对返回计数结构。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_mongosh_cross_platform_install_spec(),
case_mongosh_cli_connection_parser(),
case_mongosh_session_commands(),
case_mongosh_full_crud_walkthrough(),
]
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/mongodb-shell-lab/explore-shell.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-shell.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1770.zip