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

离线校验枚举穷尽性、增强枚举 HttpStatus、Symbol 比较及 Emoji UTF-16/Rune 码点

PYTHONWindows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。explore-enums-and-symbols.py
explore-enums-and-symbols.py211 行
"""Offline Dart 3.x semantic verification lab for Chapter 14 (enums-and-symbols)."""
import json
from enum import Enum

VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"


def case_basic_enum_and_exhaustiveness():
    class Status(Enum):
        pending = 0
        approved = 1
        rejected = 2
        cancelled = 3

    def by_name(name: str) -> Status:
        try:
            return Status[name]
        except KeyError as exc:
            raise ValueError(f"No enum value with name '{name}'") from exc

    labels = {
        Status.pending: "订单待处理",
        Status.approved: "订单已批准",
        Status.rejected: "订单被拒绝",
        Status.cancelled: "订单已取消",
    }
    exhaustive = set(labels.keys()) == set(Status)

    invalid_caught = False
    try:
        by_name("unknown")
    except ValueError:
        invalid_caught = True

    expected = {
        "pending_index": 0,
        "all_names": ["pending", "approved", "rejected", "cancelled"],
        "by_name_approved": "Status.approved",
        "invalid_by_name_throws": True,
        "switch_exhaustive": True,
        "pending_label": "订单待处理",
    }
    actual = {
        "pending_index": Status.pending.value,
        "all_names": [s.name for s in Status],
        "by_name_approved": f"Status.{by_name('approved').name}",
        "invalid_by_name_throws": invalid_caught,
        "switch_exhaustive": exhaustive,
        "pending_label": labels[Status.pending],
    }
    return {
        "name": "basic_enum_and_exhaustiveness",
        "summary": "校验基础 enum 的 .index、.values、.byName() 及 switch 穷尽性覆盖检查",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_enhanced_enum_fields_and_methods():
    class HttpStatus(Enum):
        ok = (200, "请求成功")
        created = (201, "资源已创建")
        badRequest = (400, "请求错误")
        unauthorized = (401, "未授权")
        notFound = (404, "资源未找到")
        serverError = (500, "服务器内部错误")

        def __init__(self, code: int, message: str):
            self.code = code
            self.message = message

        @property
        def is_success(self) -> bool:
            return 200 <= self.code < 300

        @property
        def is_client_error(self) -> bool:
            return 400 <= self.code < 500

        @property
        def is_server_error(self) -> bool:
            return self.code >= 500

        @classmethod
        def from_code(cls, code: int):
            for s in cls:
                if s.code == code:
                    return s
            return None

    st = HttpStatus.notFound
    found_201 = HttpStatus.from_code(201)
    found_999 = HttpStatus.from_code(999)

    expected = {
        "not_found_code": 404,
        "not_found_msg": "资源未找到",
        "is_success": False,
        "is_client_error": True,
        "is_server_error": False,
        "from_201": "资源已创建",
        "from_999": None,
    }
    actual = {
        "not_found_code": st.code,
        "not_found_msg": st.message,
        "is_success": st.is_success,
        "is_client_error": st.is_client_error,
        "is_server_error": st.is_server_error,
        "from_201": found_201.message if found_201 else None,
        "from_999": found_999,
    }
    return {
        "name": "enhanced_enum_fields_and_methods",
        "summary": "校验增强枚举的 final 字段、const 构造语义、实例计算属性与静态 fromCode 查找",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_symbol_equality_and_minification():
    class DartSymbol:
        def __init__(self, ident: str):
            self._ident = ident

        def __eq__(self, other) -> bool:
            return isinstance(other, DartSymbol) and self._ident == other._ident

        def __hash__(self) -> int:
            return hash(("DartSymbol", self._ident))

        def to_string(self, minified: bool = False) -> str:
            return 'Symbol("a")' if minified else f'Symbol("{self._ident}")'

    sym1 = DartSymbol("blueSky")
    sym2 = DartSymbol("helloWorld")
    sym3 = DartSymbol("blueSky")
    metadata = {DartSymbol("author"): "BlueSky", DartSymbol("version"): "1.0.0"}

    expected = {
        "sym1_eq_sym3": True,
        "sym1_eq_sym2": False,
        "map_lookup_author": "BlueSky",
        "unminified_str": 'Symbol("blueSky")',
        "minified_str_differs": True,
    }
    actual = {
        "sym1_eq_sym3": sym1 == sym3,
        "sym1_eq_sym2": sym1 == sym2,
        "map_lookup_author": metadata[DartSymbol("author")],
        "unminified_str": sym1.to_string(False),
        "minified_str_differs": sym1.to_string(False) != sym1.to_string(True),
    }
    return {
        "name": "symbol_equality_and_minification",
        "summary": "校验 Symbol 相等性、作为 Map 键以及压缩编译后 toString() 不可用于业务逻辑的注意事项",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_runes_and_unicode_code_points():
    text = "DART"
    ascii_points = [ord(ch) for ch in text]
    hex_labels = [f"{ch} -> U+{ord(ch):04X}" for ch in text]
    heart = chr(0x2764)
    smile = "\U0001F600"
    utf16_code_units = len(smile.encode("utf-16-le")) // 2
    rune_points = [f"U+{ord(ch):X}" for ch in smile]

    expected = {
        "ascii_points": [68, 65, 82, 84],
        "hex_labels": ["D -> U+0044", "A -> U+0041", "R -> U+0052", "T -> U+0054"],
        "heart_codepoint": "U+2764",
        "smile_utf16_units": 2,
        "smile_rune_count": 1,
        "smile_runes": ["U+1F600"],
    }
    actual = {
        "ascii_points": ascii_points,
        "hex_labels": hex_labels,
        "heart_codepoint": f"U+{ord(heart):04X}",
        "smile_utf16_units": utf16_code_units,
        "smile_rune_count": len(smile),
        "smile_runes": rune_points,
    }
    return {
        "name": "runes_and_unicode_code_points",
        "summary": "校验 Rune Unicode 码点提取、String.fromCharCode 与非 BMP Emoji 的 UTF-16 代理对差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_basic_enum_and_exhaustiveness(),
        case_enhanced_enum_fields_and_methods(),
        case_symbol_equality_and_minification(),
        case_runes_and_unicode_code_points(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。

入口文件:projects/dart-enums-and-symbols-lab/explore-enums-and-symbols.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-enums-and-symbols.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Dart

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

下载课程关联工程包:Dart

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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