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

运行修复前后的测试并检查改动范围

PYTHONCPython 3.12.14 与 Git 2.54.0.windows.1,独立临时仓库。repository_lab.py
repository_lab.py90 行
"""Practise a scoped repository change with tests and a reviewable diff."""
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory


BASE = """def label(stock):
    if stock < 0:
        raise ValueError("stock cannot be negative")
    return "ready" if stock >= 2 else "low"
"""
TESTS = """import unittest
from inventory import label


class LabelTests(unittest.TestCase):
    def test_threshold(self):
        self.assertEqual([label(0), label(1), label(2)], ["low", "ready", "ready"])

    def test_invalid_stock(self):
        with self.assertRaises(ValueError):
            label(-1)
"""


def experiment(root):
    env = {**os.environ, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull}
    for name in tuple(env):
        if name.startswith(("GIT_CONFIG_KEY_", "GIT_CONFIG_VALUE_")) or name in {
            "GIT_CONFIG", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS", "GIT_DIR", "GIT_WORK_TREE",
            "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES",
            "GIT_NAMESPACE", "GIT_TEMPLATE_DIR",
        }:
            del env[name]

    def command(*args):
        return subprocess.run(args, cwd=root, env=env, capture_output=True, encoding="utf-8", timeout=15)

    def git(*args):
        result = command("git", "-c", "core.autocrlf=false", *args)
        result.check_returncode()
        return result.stdout

    source = root / "inventory.py"
    source.write_text(BASE, encoding="utf-8", newline="\n")
    (root / "test_inventory.py").write_text(TESTS, encoding="utf-8", newline="\n")
    (root / "README.md").write_text("Inventory lab\n", encoding="utf-8", newline="\n")
    git("init", "--quiet", "--initial-branch=main", "--template=")
    git("add", "--", "inventory.py", "test_inventory.py", "README.md")
    git("-c", "user.name=Fixture Author", "-c", "user.email=fixture@example.invalid", "commit", "--quiet", "-m", "Baseline")
    initial = git("status", "--porcelain=v1").splitlines()

    def tests():
        return command(sys.executable, "-I", "-B", "-c",
                       "import sys, unittest; sys.path.insert(0, '.'); unittest.main(module='test_inventory', verbosity=2)")

    failing = tests()
    assert failing.returncode == 1 and "test_threshold" in failing.stderr
    assert "AssertionError" in failing.stderr and "Ran 2 tests" in failing.stderr
    source.write_text(BASE.replace("stock >= 2", "stock >= 1"), encoding="utf-8", newline="\n")
    passing = tests()
    assert passing.returncode == 0 and "Ran 2 tests" in passing.stderr and passing.stderr.rstrip().endswith("OK")
    changed = git("status", "--porcelain=v1").splitlines()
    diff = git("diff", "--no-ext-diff", "--", "inventory.py")
    assert initial == [] and changed == [" M inventory.py"]
    assert '-    return "ready" if stock >= 2 else "low"' in diff
    assert '+    return "ready" if stock >= 1 else "low"' in diff
    assert git("diff", "--name-only", "--", "test_inventory.py", "README.md") == ""
    assert git("diff", "--cached", "--name-only") == "" and git("remote") == ""
    return {
        "version": {"python": sys.version.split()[0], "git": git("--version").strip()},
        "cases": [
            dict(name="codex_intro_red_green", input={"stock": [-1, 0, 1, 2], "threshold": [2, 1]},
                 operation="Run the same two Python tests before and after the one-line change",
                 expected=[1, 0, 2], actual=[failing.returncode, passing.returncode, 2]),
            dict(name="codex_intro_diff_scope", input="a clean temporary Git repository with three tracked files",
                 operation="Inspect status, the change, staged files and configured remotes",
                 expected=[[], [" M inventory.py"], [], []],
                 actual=[initial, changed, git("diff", "--cached", "--name-only").splitlines(), git("remote").splitlines()]),
        ],
    }


if __name__ == "__main__":
    with TemporaryDirectory(prefix="mbsky-codex-intro-fixture-") as temp:
        print(json.dumps(experiment(Path(temp)), ensure_ascii=False))
本例需在 CPython 3.12.14 与 Git 2.54.0.windows.1,独立临时仓库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12.14 与 Git 2.54.0.windows.1,独立临时仓库。

入口文件:projects/codex-intro/repository_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 repository_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12.14 与 Git 2.54.0.windows.1,独立临时仓库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Codex 教程

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

下载课程关联工程包:Codex 教程

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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