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

运行 db.dropDatabase() 全流程、默认 test 库删除、collection.drop() 及空库幂等删除验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-dropdatabase.py
explore-dropdatabase.py150 行
"""Offline MongoDB dropDatabase() & collection.drop() verifier (Ch12 dropdatabase)."""
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


class MiniMongoDropStore:
    def __init__(self):
        self.dbs = {
            "admin": {"system.version": [{}]},
            "config": {"system.sessions": [{}]},
            "local": {"startup_log": [{}]},
            "demo_db": {"site": [{"name": "蓝色天空网"}], "logs": [{"msg": "init"}]},
            "test": {"scratch": [{"v": 1}]},
        }
        self.current_db = "test"

    def show_dbs(self):
        return sorted(db for db, cols in self.dbs.items() if cols)

    def use(self, name: str):
        self.current_db = name

    def show_collections(self):
        return sorted(self.dbs.get(self.current_db, {}).keys())

    def create_collection(self, col: str):
        self.dbs.setdefault(self.current_db, {}).setdefault(col, [])

    def drop_database(self):
        if self.current_db in self.dbs:
            del self.dbs[self.current_db]
            return {"dropped": self.current_db, "ok": 1}
        return {"ok": 1}

    def drop_collection(self, col: str) -> bool:
        db_cols = self.dbs.get(self.current_db, {})
        if col in db_cols:
            del db_cols[col]
            return True
        return False


def case_drop_database_workflow():
    st = MiniMongoDropStore()
    before = st.show_dbs()
    st.use("demo_db")
    res = st.drop_database()
    after = st.show_dbs()
    actual = {
        "before_has_demo_db": "demo_db" in before,
        "drop_response": res,
        "after_has_demo_db": "demo_db" in after,
        "system_dbs_intact": all(k in after for k in ("admin", "config", "local")),
    }
    expected = {
        "before_has_demo_db": True,
        "drop_response": {"dropped": "demo_db", "ok": 1},
        "after_has_demo_db": False,
        "system_dbs_intact": True,
    }
    return {
        "name": "drop_database_workflow",
        "summary": "验证 show dbs -> use demo_db -> db.dropDatabase() -> show dbs 全流程及返回值。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_default_test_database():
    st = MiniMongoDropStore()
    default_before = st.current_db
    res = st.drop_database()
    actual = {
        "default_target": default_before,
        "drop_response": res,
        "demo_db_untouched": "demo_db" in st.show_dbs(),
    }
    expected = {
        "default_target": "test",
        "drop_response": {"dropped": "test", "ok": 1},
        "demo_db_untouched": True,
    }
    return {
        "name": "drop_default_test_database",
        "summary": "验证未切换库时 db.dropDatabase() 默认删除当前 test 数据库而不影响其他库。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_collection_workflow():
    st = MiniMongoDropStore()
    st.use("demo_db")
    st.create_collection("temp_col")
    cols_before = st.show_collections()
    first_drop = st.drop_collection("temp_col")
    second_drop = st.drop_collection("temp_col")
    cols_after = st.show_collections()
    actual = {
        "cols_before": cols_before,
        "first_drop": first_drop,
        "second_drop": second_drop,
        "cols_after": cols_after,
    }
    expected = {
        "cols_before": ["logs", "site", "temp_col"],
        "first_drop": True,
        "second_drop": False,
        "cols_after": ["logs", "site"],
    }
    return {
        "name": "drop_collection_workflow",
        "summary": "验证 db.collection.drop() 删除已有集合返回 true、再次删除返回 false 并更新 show collections。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_idempotent_drop_empty_db():
    st = MiniMongoDropStore()
    st.use("ghost_db")
    res = st.drop_database()
    actual = {"response": res, "admin_intact": "admin" in st.show_dbs()}
    expected = {"response": {"ok": 1}, "admin_intact": True}
    return {
        "name": "idempotent_drop_empty_db",
        "summary": "验证对未落盘或空数据库调用 db.dropDatabase() 安全返回 {ok: 1} 且不波及系统库。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_drop_database_workflow(),
        case_drop_default_test_database(),
        case_drop_collection_workflow(),
        case_idempotent_drop_empty_db(),
    ]
    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-dropdatabase-lab/explore-dropdatabase.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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