Python 模擬試験

Python実践 模擬試験 第5回 問36・16章 テスト(doctest)

ELLIPSIS

次のコードを実行したときの出力として、正しいものを1つ選べ。

import doctest, io, contextlib
def f():
    """
    >>> print("a1b")
    a...b
    """
def run(flags):
    t = doctest.DocTestFinder().find(f, "f", globs={"f": f})[0]
    with contextlib.redirect_stdout(io.StringIO()):
        return doctest.DocTestRunner(optionflags=flags).run(t).failed
print(run(doctest.ELLIPSIS), run(0))
  1. A

    1 0

  2. B

    0 0

  3. C

    1 1

  4. D

    0 1

正解と解説を見る

正解:D

doctest のオプション ELLIPSIS は、期待する出力の ... を、任意の文字列に一致させる。メモリアドレスなど、毎回変わる出力を含むときに使う。

順実行する行実行後の変数
1`import doctest, io, contextlib`—
2`def f():`—
3`def run(flags):`—
4`print(run(doctest.ELLIPSIS), run(0))`—
5└ `t = doctest.DocTestFinder().find(f, "f", glob…`—
6└ `with contextlib.redirect_stdout(io.StringIO()…`—
7└ `return doctest.DocTestRunner(optionflags=flag…`flags = 8
8└ `with contextlib.redirect_stdout(io.StringIO()…`—
9└ `t = doctest.DocTestFinder().find(f, "f", glob…`—
10└ `with contextlib.redirect_stdout(io.StringIO()…`—
11└ `return doctest.DocTestRunner(optionflags=flag…`flags = 0
12└ `with contextlib.redirect_stdout(io.StringIO()…`—
結果実際の出力0 1

学習のポイント:NORMALIZE_WHITESPACE で、空白の違いを無視できる。

この問題を演習で解く →

問題一覧へ

このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。