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

运行 Windows mongod.cfg 配置解析、服务状态机及默认 test 库写入离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-window-install.py
explore-window-install.py149 行
"""Offline Windows MongoDB installation, YAML config, service FSM & Shell verifier (Ch04 window-install)."""
import json
import ntpath
import re

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


def parse_simple_yaml(text: str) -> dict:
    result = {}
    section = None
    for raw in text.splitlines():
        line = raw.rstrip()
        if not line.strip() or line.strip().startswith("#"):
            continue
        if not raw.startswith(" ") and line.endswith(":"):
            section = line[:-1].strip()
            result[section] = {}
        elif section is not None and ":" in line:
            k, v = line.strip().split(":", 1)
            result[section][k.strip()] = v.strip()
    return result


def case_windows_msi_architecture_and_paths():
    db_path = ntpath.normpath(r"C:\data\db")
    log_dir = ntpath.normpath(r"C:\data\log")
    log_file = ntpath.join(log_dir, "mongod.log")
    legacy_32bit_limit_gb = 2
    actual = {
        "db_path": db_path,
        "log_file": log_file,
        "is_absolute_root_drive": ntpath.isabs(db_path),
        "legacy_32bit_limit_gb": legacy_32bit_limit_gb,
        "modern_64bit_only": True,
    }
    expected = {
        "db_path": r"C:\data\db",
        "log_file": r"C:\data\log\mongod.log",
        "is_absolute_root_drive": True,
        "legacy_32bit_limit_gb": 2,
        "modern_64bit_only": True,
    }
    return {
        "name": "windows_msi_architecture_and_paths",
        "summary": "验证 Windows 64 位安装包要求、历史 32 位 2GB 上限及数据/日志根目录规范化。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mongod_cfg_yaml_config_parser():
    cfg_text = (
        "systemLog:\n"
        "    destination: file\n"
        "    path: c:\\data\\log\\mongod.log\n"
        "storage:\n"
        "    dbPath: c:\\data\\db\n"
    )
    parsed = parse_simple_yaml(cfg_text)
    install_cmd = 'mongod --config "C:\\mongodb\\mongod.cfg" --install --serviceName MongoDB --serviceDisplayName MongoDB'
    has_required_flags = all(flag in install_cmd for flag in ("--config", "--install", "--serviceName"))
    actual = {
        "log_destination": parsed["systemLog"]["destination"],
        "log_path": parsed["systemLog"]["path"],
        "db_path": parsed["storage"]["dbPath"],
        "has_required_flags": has_required_flags,
    }
    expected = {
        "log_destination": "file",
        "log_path": r"c:\data\log\mongod.log",
        "db_path": r"c:\data\db",
        "has_required_flags": True,
    }
    return {
        "name": "mongod_cfg_yaml_config_parser",
        "summary": "解析 Windows mongod.cfg YAML 配置项(systemLog.path 与 storage.dbPath)并校验服务安装参数。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_windows_service_lifecycle_fsm():
    state = "not_installed"
    history = [state]
    transitions = [
        ("mongod --config C:\\mongodb\\mongod.cfg --install", "stopped"),
        ("net start MongoDB", "running"),
        ("net stop MongoDB", "stopped"),
        ("mongod --remove", "not_installed"),
    ]
    for _cmd, nxt in transitions:
        state = nxt
        history.append(state)
    expected = ["not_installed", "stopped", "running", "stopped", "not_installed"]
    return {
        "name": "windows_service_lifecycle_fsm",
        "summary": "模拟 Windows 下 MongoDB 服务注册、net start 启动、net stop 停止与 --remove 移除状态机。",
        "expected": expected,
        "actual": history,
        "passed": history == expected,
    }


def case_shell_default_test_db_and_crud():
    dbs = {"test": {"demo": []}}
    current_db = "test"
    arith = 2 + 2
    inserted = {"_id": "5604ff74a274a611b0c990aa", "x": 10}
    dbs[current_db]["demo"].append(inserted)
    found = list(dbs[current_db]["demo"])
    actual = {
        "default_db": current_db,
        "js_eval_2_plus_2": arith,
        "inserted_count": len(found),
        "first_doc_x": found[0]["x"],
        "id_is_24_hex": bool(re.fullmatch(r"[0-9a-f]{24}", found[0]["_id"])),
    }
    expected = {
        "default_db": "test",
        "js_eval_2_plus_2": 4,
        "inserted_count": 1,
        "first_doc_x": 10,
        "id_is_24_hex": True,
    }
    return {
        "name": "shell_default_test_db_and_crud",
        "summary": "验证 Shell 默认连接 test 库、基础算术求值、插入 {x: 10} 与 ObjectId 检索结果。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_windows_msi_architecture_and_paths(),
        case_mongod_cfg_yaml_config_parser(),
        case_windows_service_lifecycle_fsm(),
        case_shell_default_test_db_and_crud(),
    ]
    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-window-install-lab/explore-window-install.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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