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

在隔离工作目录内复现、修复并复核库存缺陷

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。workflow.py
workflow.py85 行
"""Exercise a test-first fix in a disposable Git repository."""
import argparse
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory


TESTS = """import unittest
from reservation import remaining

class ReservationTests(unittest.TestCase):
    def test_stock_remains(self):
        self.assertEqual(remaining(12, 3), 9)

    def test_overbooking_leaves_zero(self):
        self.assertEqual(remaining(2, 7), 0)
"""
BASE = "def remaining(stock, held):\n    return stock - held\n"
FIXED = "def remaining(stock, held):\n    return max(stock - held, 0)\n"
REFACTORED = ("def remaining(stock, held):\n"
              "    available = stock - held\n"
              "    return max(available, 0)\n")
PLAN = [
    {"file": "test_reservation.py", "change": "Record the failing overbooking case", "check": "unittest"},
    {"file": "reservation.py", "change": "Return zero when stock is exhausted", "check": "unittest"},
]


def run_experiment():
    git = shutil.which("git")
    if not git:
        raise RuntimeError("Git is required for the isolated repository demonstration.")
    env = dict(os.environ, GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0")
    with TemporaryDirectory(prefix="skills-workflow-") as temp:
        root = Path(temp)
        main = root / "project"
        topic = root / "review"

        def run_git(folder, *args):
            return subprocess.check_output(
                [git, "-C", str(folder), *args], env=env, encoding="utf-8", stderr=subprocess.PIPE, timeout=12
            ).strip()

        main.mkdir()
        run_git(main, "init", "-b", "main")
        (main / "reservation.py").write_text(BASE, encoding="utf-8")
        run_git(main, "add", "reservation.py")
        run_git(main, "-c", "user.name=Local Example", "-c", "user.email=example@invalid.test",
                "commit", "-m", "Record the original stock calculation")
        run_git(main, "worktree", "add", "-b", "work/limit", str(topic))
        base_hash = run_git(main, "rev-parse", "HEAD")
        branches = [run_git(main, "branch", "--show-current"), run_git(topic, "branch", "--show-current")]

        (topic / "test_reservation.py").write_text(TESTS, encoding="utf-8")
        outcomes = []
        for phase, code in (("RED", BASE), ("GREEN", FIXED), ("REFACTOR", REFACTORED)):
            (topic / "reservation.py").write_text(code, encoding="utf-8")
            result = subprocess.run([sys.executable, "-B", "-X", "utf8", "-m", "unittest",
                                     "-v", "test_reservation.py"], cwd=topic, encoding="utf-8",
                                    capture_output=True, timeout=12)
            failure = next((line for line in result.stderr.splitlines() if line.startswith("AssertionError:")), None)
            outcomes.append({"phase": phase, "exit": result.returncode, "failure": failure,
                             "cases": sum(line.startswith("test_") for line in result.stderr.splitlines()),
                             "implementation_sha256": sha256(code.encode()).hexdigest()})

        changed = run_git(topic, "diff", "--name-only").splitlines()
        main_untouched = (main / "reservation.py").read_text(encoding="utf-8") == BASE and (
            run_git(main, "rev-parse", "HEAD") == base_hash and not run_git(main, "status", "--porcelain")
        )
        return {"git": run_git(main, "--version"), "branches": branches, "main_untouched": main_untouched,
                "test_sha256": sha256(TESTS.encode()).hexdigest(), "plan": PLAN, "outcomes": outcomes,
                "review": {"specification": outcomes[-1]["exit"] == 0,
                           "scope": changed == ["reservation.py"], "tracked_changes": changed}}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.parse_args()
    print(json.dumps(run_experiment(), ensure_ascii=False))
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

入口文件:projects/skills-workflow-design/workflow.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 workflow.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Skills(技能)

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

下载课程关联工程包:Skills(技能)

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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