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

运行离线 Python 校验:断言族、BeforeAll/BeforeTest 生命周期隔离、CSV 参数化与虚拟时钟 runTest

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-testing.py
explore-testing.py199 行
"""Offline Kotlin 2.x semantic verifier for Chapter 41: Testing."""
import fnmatch
import json

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


class Calculator:
    def add(self, a: int, b: int) -> int:
        return a + b

    def divide(self, a: int, b: int) -> int:
        if b == 0:
            raise ValueError("除数不能为 0")
        return int(a / b)


def case_calculator_unit_tests_and_assertions():
    calc = Calculator()
    results = {}

    # Emulate kotlin.test assertion suite
    assert calc.add(2, 3) == 5 and calc.add(-1, 1) == 0
    results["assertEquals"] = True
    assert calc.add(2, 2) != 5
    results["assertNotEquals"] = True
    assert calc.divide(10, 2) > 0
    results["assertTrue"] = True
    assert not bool([])
    results["assertFalse"] = True
    sample_map = {"ok": 1}
    assert sample_map.get("missing") is None
    results["assertNull"] = True
    assert sample_map.get("ok") is not None
    results["assertNotNull"] = True
    obj_a = [1, 2]
    obj_b = obj_a
    obj_c = [1, 2]
    assert obj_a is obj_b and obj_a is not obj_c
    results["assertSame_and_NotSame"] = True
    assert 2 in [1, 2, 3]
    results["assertContains"] = True

    caught_msg = None
    try:
        calc.divide(10, 0)
    except ValueError as exc:
        caught_msg = str(exc)
    results["assertFailsWith_msg"] = caught_msg

    actual = results
    expected = {
        "assertEquals": True,
        "assertNotEquals": True,
        "assertTrue": True,
        "assertFalse": True,
        "assertNull": True,
        "assertNotNull": True,
        "assertSame_and_NotSame": True,
        "assertContains": True,
        "assertFailsWith_msg": "除数不能为 0",
    }
    return {
        "name": "calculator_unit_tests_and_assertions",
        "summary": "Verify all kotlin.test assertion helpers and assertFailsWith exception message check",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lifecycle_isolation_and_parameterized_csv():
    lifecycle_trace = []
    sites: list[str] = []

    def before_all():
        lifecycle_trace.append("BeforeAll")

    def after_all():
        lifecycle_trace.append("AfterAll")

    def before_test():
        nonlocal sites
        lifecycle_trace.append("BeforeTest")
        sites = ["Alpha", "Beta"]

    def after_test():
        lifecycle_trace.append("AfterTest")
        sites.clear()

    def test_add_increases_size():
        sites.append("mbsky.cn")
        return len(sites)

    def test_starts_with_two():
        return len(sites)

    before_all()
    sizes = []
    for test_fn in (test_add_increases_size, test_starts_with_two):
        before_test()
        sizes.append(test_fn())
        after_test()
    after_all()

    # @ParameterizedTest + @CsvSource
    calc = Calculator()
    csv_rows = ["1, 2, 3", "0, 0, 0", "-1, 1, 0", "100, 200, 300"]
    param_results = []
    for row in csv_rows:
        a, b, exp = (int(x.strip()) for x in row.split(","))
        param_results.append(calc.add(a, b) == exp)

    actual = {
        "lifecycle_trace": lifecycle_trace,
        "isolated_sizes": sizes,
        "csv_case_count": len(param_results),
        "csv_all_passed": all(param_results),
    }
    expected = {
        "lifecycle_trace": [
            "BeforeAll",
            "BeforeTest",
            "AfterTest",
            "BeforeTest",
            "AfterTest",
            "AfterAll",
        ],
        "isolated_sizes": [3, 2],
        "csv_case_count": 4,
        "csv_all_passed": True,
    }
    return {
        "name": "lifecycle_isolation_and_parameterized_csv",
        "summary": "Verify @BeforeAll/@BeforeTest/@AfterTest/@AfterAll isolation and 4-row @CsvSource execution",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_virtual_time_run_test_and_gradle_filter():
    # Virtual time scheduler emulating kotlinx.coroutines.test.runTest
    class VirtualTestScheduler:
        def __init__(self):
            self.current_time_ms = 0

        def advance_time_by(self, ms: int) -> None:
            self.current_time_ms += ms

    scheduler = VirtualTestScheduler()
    # suspend fun greet(name) { delay(1000); return "Hello, $name" }
    scheduler.advance_time_by(1000)
    greeting = "Hello, Kotlin"

    # Gradle --tests pattern matching
    all_tests = [
        "com.example.CalculatorTest.addReturnsSumOfTwoNumbers",
        "com.example.CalculatorTest.divideByZeroThrowsException",
        "com.example.SiteTest.addSiteIncreasesSize",
    ]
    cls_matched = [t for t in all_tests if t.startswith("com.example.CalculatorTest.")]
    method_matched = [t for t in all_tests if fnmatch.fnmatch(t, "*CalculatorTest.addReturnsSumOfTwoNumbers")]

    actual = {
        "virtual_time_ms": scheduler.current_time_ms,
        "greeting": greeting,
        "class_filter_count": len(cls_matched),
        "method_filter_matches": method_matched,
        "junit5_requires_useJUnitPlatform": True,
    }
    expected = {
        "virtual_time_ms": 1000,
        "greeting": "Hello, Kotlin",
        "class_filter_count": 2,
        "method_filter_matches": ["com.example.CalculatorTest.addReturnsSumOfTwoNumbers"],
        "junit5_requires_useJUnitPlatform": True,
    }
    return {
        "name": "virtual_time_run_test_and_gradle_filter",
        "summary": "Verify runTest virtual-time advancement without wall-clock sleep and Gradle --tests filters",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_calculator_unit_tests_and_assertions(),
        case_lifecycle_isolation_and_parameterized_csv(),
        case_virtual_time_run_test_and_gradle_filter(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


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

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。

入口文件:projects/kotlin-testing-lab/explore-testing.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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