"""Offline MongoDB createCollection options, capped eviction, $jsonSchema & collation verifier (Ch13)."""
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def validate_json_schema(doc: dict, schema: dict) -> tuple[bool, str]:
if schema.get("bsonType") == "object" and not isinstance(doc, dict):
return False, "not_object"
for req in schema.get("required", []):
if req not in doc:
return False, f"missing_{req}"
for field, rule in schema.get("properties", {}).items():
if field not in doc:
continue
val = doc[field]
bt = rule.get("bsonType")
if bt == "string" and not isinstance(val, str):
return False, f"{field}_not_string"
if bt == "int" and (isinstance(val, bool) or not isinstance(val, int)):
return False, f"{field}_not_int"
if "pattern" in rule and isinstance(val, str) and not re.search(rule["pattern"], val):
return False, f"{field}_pattern_mismatch"
if "minimum" in rule and isinstance(val, (int, float)) and val < rule["minimum"]:
return False, f"{field}_below_minimum"
return True, "ok"
class OfflineCollection:
def __init__(self, name: str, options: dict | None = None):
self.name = name
self.options = options or {}
self.docs = []
self.warnings = []
self.cur_bytes = 0
def insert_one(self, doc: dict):
level = self.options.get("validationLevel", "strict")
action = self.options.get("validationAction", "error")
schema = (self.options.get("validator") or {}).get("$jsonSchema")
if schema and level == "strict":
ok, reason = validate_json_schema(doc, schema)
if not ok:
if action == "error":
return {"ok": False, "error": reason}
self.warnings.append(reason)
rec = dict(doc)
sz = len(json.dumps(rec, ensure_ascii=False).encode("utf-8"))
self.docs.append((rec, sz))
self.cur_bytes += sz
if self.options.get("capped"):
max_size = self.options.get("size")
max_docs = self.options.get("max")
# MongoDB checks size first, then max
while (max_size is not None and self.cur_bytes > max_size) or (
max_docs is not None and len(self.docs) > max_docs
):
_, old_sz = self.docs.pop(0)
self.cur_bytes -= old_sz
return {"ok": True}
def case_basic_and_implicit_collection_creation():
collections = {}
collections["demo"] = OfflineCollection("demo")
explicit_ok = "demo" in collections
# Implicit creation on first insert
collections.setdefault("mycol2", OfflineCollection("mycol2")).insert_one({"name": "蓝色天空网"})
actual = {
"explicit_created": explicit_ok,
"collections": sorted(collections.keys()),
"mycol2_count": len(collections["mycol2"].docs),
}
expected = {
"explicit_created": True,
"collections": ["demo", "mycol2"],
"mycol2_count": 1,
}
return {
"name": "basic_and_implicit_collection_creation",
"summary": "验证 db.createCollection() 显式建集合与首次插入文档时隐式自动建集合。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_capped_collection_size_and_max_eviction():
col = OfflineCollection("myCappedCollection", {"capped": True, "size": 100, "max": 3})
for i in range(1, 6):
col.insert_one({"id": i, "tag": f"log-{i}"})
remaining_ids = [d["id"] for d, _ in col.docs]
actual = {
"remaining_ids": remaining_ids,
"within_size": col.cur_bytes <= 100,
"within_max": len(col.docs) <= 3,
}
expected = {"remaining_ids": [3, 4, 5], "within_size": True, "within_max": True}
return {
"name": "capped_collection_size_and_max_eviction",
"summary": "验证固定集合同时受 size(字节)与 max(文档数)约束时先检查 size 再检查 max 的 FIFO 淘汰。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_jsonschema_validator_strict_moderate_off():
schema = {
"$jsonSchema": {
"bsonType": "object",
"required": ["name", "age"],
"properties": {
"name": {"bsonType": "string"},
"age": {"bsonType": "int", "minimum": 0},
},
}
}
strict_err = OfflineCollection("c1", {"validator": schema, "validationLevel": "strict", "validationAction": "error"})
strict_warn = OfflineCollection("c2", {"validator": schema, "validationLevel": "strict", "validationAction": "warn"})
off_col = OfflineCollection("c3", {"validator": schema, "validationLevel": "off"})
bad_doc = {"name": "Bob", "age": -3}
good_doc = {"name": "Alice", "age": 28}
r_bad_err = strict_err.insert_one(bad_doc)
r_good_err = strict_err.insert_one(good_doc)
r_bad_warn = strict_warn.insert_one(bad_doc)
r_bad_off = off_col.insert_one(bad_doc)
actual = {
"strict_error_rejects_bad": r_bad_err,
"strict_error_accepts_good": r_good_err["ok"],
"strict_warn_allows_and_logs": [r_bad_warn["ok"], strict_warn.warnings],
"off_allows_bad": r_bad_off["ok"],
}
expected = {
"strict_error_rejects_bad": {"ok": False, "error": "age_below_minimum"},
"strict_error_accepts_good": True,
"strict_warn_allows_and_logs": [True, ["age_below_minimum"]],
"off_allows_bad": True,
}
return {
"name": "jsonschema_validator_strict_moderate_off",
"summary": "验证 $jsonSchema 必填与类型/最小值校验,以及 validationLevel(strict/off) 与 validationAction(error/warn)。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_complex_collection_options_storage_collation():
opts = {
"capped": True,
"size": 10485760,
"max": 5000,
"validator": {
"$jsonSchema": {
"bsonType": "object",
"required": ["name", "email"],
"properties": {
"name": {"bsonType": "string"},
"email": {"bsonType": "string", "pattern": r"^.+@.+$"},
},
}
},
"validationLevel": "strict",
"validationAction": "error",
"storageEngine": {"wiredTiger": {"configString": "block_compressor=zstd"}},
"collation": {"locale": "en", "strength": 2},
}
col = OfflineCollection("myComplexCollection", opts)
r1 = col.insert_one({"name": "Alice", "email": "alice@example.com"})
r2 = col.insert_one({"name": "Bob", "email": "invalid-email"})
# strength=2 compares base characters & accents, ignoring case in en locale
ci_equal = "Cafe".casefold() == "cafe".casefold()
actual = {
"valid_email_inserted": r1["ok"],
"bad_email_error": r2["error"],
"compressor": opts["storageEngine"]["wiredTiger"]["configString"],
"collation_strength2_case_insensitive": ci_equal,
}
expected = {
"valid_email_inserted": True,
"bad_email_error": "email_pattern_mismatch",
"compressor": "block_compressor=zstd",
"collation_strength2_case_insensitive": True,
}
return {
"name": "complex_collection_options_storage_collation",
"summary": "验证综合建集合配置:capped、email 正则验证器、WiredTiger zstd 压缩及 en strength:2 排序规则。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_collection_options_table_contract():
option_names = [
"capped",
"size",
"max",
"validator",
"validationLevel",
"validationAction",
"storageEngine",
"collation",
]
actual = {"option_count": len(option_names), "defaults": {"validationLevel": "strict", "validationAction": "error"}}
expected = {"option_count": 8, "defaults": {"validationLevel": "strict", "validationAction": "error"}}
return {
"name": "collection_options_table_contract",
"summary": "核对 createCollection 全部 8 个选项参数清单与默认校验行为。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_basic_and_implicit_collection_creation(),
case_capped_collection_size_and_max_eviction(),
case_jsonschema_validator_strict_moderate_off(),
case_complex_collection_options_storage_collation(),
case_collection_options_table_contract(),
]
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-create-collection-lab/explore-create-collection.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-create-collection.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1737.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip