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

运行本章核心实例

PYTHONCPython text-memory stream positions, line hints, lifecycle and real unittestpython-stringio.py
python-stringio.py142 行
"""Observe a text stream in memory and run a real stream-based unit test."""

import io
import json
import sys
import unittest
from contextlib import redirect_stdout


def transform(source, destination):
    """Read a text stream and write its upper-case form to another."""
    destination.write(source.read().upper())


class TransformTest(unittest.TestCase):
    def test_transform_with_memory_streams(self):
        with io.StringIO("pier 7\n北港") as source, io.StringIO() as destination:
            transform(source, destination)
            self.assertEqual(destination.getvalue(), "PIER 7\n北港")


def observe():
    checks = []

    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        checks.append(dict(name=name, input=inputs, operation=operation, actual=actual,
                           expected=expected, passed=True))

    def rejects(name, error_type, inputs, operation, call):
        try:
            call()
        except error_type as exc:
            check(name, type(exc).__name__, error_type.__name__, inputs, operation)
        else:
            raise AssertionError(name)

    with io.StringIO() as stream:
        check("empty StringIO opens at position zero",
              [stream.getvalue(), stream.tell(), stream.closed], ["", 0, False], "no initial value",
              "Create an open memory stream and inspect its initial state")
        counts = [stream.write("北港\n"), stream.write("🚢二号")]
        check("writes count Unicode characters and advance",
              [counts, stream.tell(), stream.getvalue()], [[3, 3], 6, "北港\n🚢二号"],
              ["北港\n", "🚢二号"], "Write two chunks and check count, content, and current position")
        rejects("text stream rejects bytes", TypeError, "UTF-8 bytes", "Try writing bytes to a text stream",
                lambda: stream.write(b"pier"))
        check("read from end returns empty", stream.read(), "", "at end of stream", "Read without moving the position")
        check("seek to start before full read", [stream.seek(0), stream.read()], [0, "北港\n🚢二号"],
              "two previously written chunks", "Rewind and read all remaining text")
        stream.seek(0)
        read = stream.read(2)
        before = stream.tell()
        content = stream.getvalue()
        check("getvalue does not advance and includes already read text",
              [read, before, content, stream.tell(), stream.read(-1)], ["北港", 2, "北港\n🚢二号", 2, "\n🚢二号"],
              "cursor after two characters", "Read a prefix, retrieve full contents, and read the remaining text")
    check("context exit marks stream closed", stream.closed, True, "previous with block", "Inspect the closed attribute")
    check("close is idempotent", stream.close(), None, "already closed stream", "Close the stream again")
    rejects("closed stream read fails", ValueError, "closed stream", "Attempt to read", stream.read)
    rejects("closed stream getvalue fails", ValueError, "closed stream", "Attempt to retrieve content", stream.getvalue)

    with io.StringIO("舰🚢位") as stream:
        check("initial value starts at beginning", [stream.tell(), stream.read(2)], [0, "舰🚢"],
              "Unicode plus one supplementary code point", "Read the first two characters")
        pos = stream.tell()
        check("read zero does not move cursor", [stream.read(0), stream.tell()], ["", pos],
              "non-EOF position", "Request zero characters and check the saved cursor")
        check("initial overwrite and explicit append", [stream.seek(0), stream.write("港"), stream.seek(0, 2),
              stream.write("站"), stream.getvalue()], [0, 1, 3, 1, "港🚢位站"], "initialized stream",
              "Overwrite at start, then move to end and append one character")
        check("seek zero relative to current keeps position", stream.seek(0, 1), 4,
              "at end of current text", "Seek a zero displacement from current position")
        rejects("nonzero current seek unsupported", OSError, "seek(1, 1)", "Try a nonzero relative current seek",
                lambda: stream.seek(1, 1))
        rejects("nonzero end seek unsupported", OSError, "seek(-1, 2)", "Try a nonzero relative end seek",
                lambda: stream.seek(-1, 2))
        rejects("negative absolute seek rejected", ValueError, "seek(-1)", "Try seeking before position zero",
                lambda: stream.seek(-1))
        check("absolute seek uses StringIO character index", [stream.seek(1), stream.read(1), stream.tell()],
              [1, "🚢", 2], "known supplementary character at index 1", "Seek to and read a single Unicode character")

    with io.StringIO("蓝湾\n\n尾") as stream:
        actual = [stream.readline(1), stream.readline(), stream.readline(), stream.readline(), stream.readline()]
        check("readline distinguishes size blank line and EOF", actual, ["蓝", "湾\n", "\n", "尾", ""],
              "one ordinary line, one blank line, and unterminated final line", "Read with a bound and then through EOF")
    with io.StringIO("甲乙\n丙丁\n戊\n") as stream:
        actual = [stream.readlines(3), stream.readlines(), stream.tell()]
        check("readlines hint stops after complete lines exceed threshold",
              actual, [["甲乙\n", "丙丁\n"], ["戊\n"], 8], "hint=3",
              "Read whole lines until cumulative characters exceed hint, then read the remainder")
    with io.StringIO("a\nb") as stream:
        check("readlines nonpositive hint does not limit",
              [stream.readlines(0), stream.seek(0), stream.readlines(-1)], [["a\n", "b"], 0, ["a\n", "b"]],
              "same input with zero and negative hints", "Compare remaining full-line lists")

    with io.StringIO("甲乙丙丁") as stream:
        stream.seek(2)
        check("truncate defaults to cursor without moving",
              [stream.truncate(), stream.getvalue(), stream.tell()], [2, "甲乙", 2],
              "cursor at index 2", "Truncate without a size and inspect text and cursor")
        check("explicit truncate leaves cursor beyond shortened text",
              [stream.truncate(1), stream.getvalue(), stream.tell()], [1, "甲", 2],
              "requested size 1 at cursor 2", "Shorten content explicitly and inspect retained position")
        check("large truncate size does not grow CPython StringIO",
              [stream.truncate(4), stream.getvalue(), stream.tell()], [4, "甲", 2],
              "requested size 4 for length 1", "Compare reported size to actual text in this runtime")
        check("write beyond end fills an observed gap",
              [stream.seek(3), stream.read(), stream.write("乙"), stream.getvalue()],
              [3, "", 1, "甲\0\0乙"], "seek to index 3 beyond length 1",
              "Read from beyond end, then write at that position")

    for newline, expected in ((None, "甲\n乙\n丙\n"), ("", "甲\r\n乙\r丙\n"), ("\r\n", "甲\r\r\n乙\r丙\r\n")):
        with io.StringIO(newline=newline) as stream:
            count = stream.write("甲\r\n乙\r丙\n")
            check("newline policy " + repr(newline), [count, stream.getvalue()], [7, expected],
                  {"newline": newline, "input": "甲\r\n乙\r丙\n"}, "Write mixed line endings and compare stored text")

    with io.StringIO() as target:
        suite = unittest.TestSuite([TransformTest("test_transform_with_memory_streams")])
        result = unittest.TextTestRunner(stream=target, verbosity=2).run(suite)
        check("real unittest tests both memory streams",
              [result.testsRun, result.wasSuccessful(), "test_transform_with_memory_streams" in target.getvalue()],
              [1, True, True], "test fixture and independent runner output",
              "Run a unittest and confirm its asserted transformation and captured report")
    original = sys.stdout
    with io.StringIO() as target:
        with redirect_stdout(target):
            print("港口就绪")
        check("redirected print and original stdout restored",
              [target.getvalue(), sys.stdout is original], ["港口就绪\n", True],
              "redirect_stdout with a memory stream", "Capture text and verify stdout restored by identity")
    with io.BytesIO(b"\xe5\x8c\x97") as binary:
        check("BytesIO works in bytes instead of text", [binary.read(1).hex(), binary.tell()],
              ["e5", 1], "UTF-8 bytes for 北", "Read one byte and inspect the byte position")
    return checks


if __name__ == "__main__":
    print(json.dumps(observe(), ensure_ascii=True, indent=2))
本例需在 CPython text-memory stream positions, line hints, lifecycle and real unittest 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython text-memory stream positions, line hints, lifecycle and real unittest

入口文件:projects/python-lab/python-stringio.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-stringio.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython text-memory stream positions, line hints, lifecycle and real unittest。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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