Python 模擬試験

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

doctest の実行結果

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

import doctest, io, contextlib
def add(a, b):
    """
    >>> add(1, 2)
    3
    >>> add(2, 2)
    5
    """
    return a + b
t = doctest.DocTestFinder().find(add, "add", globs={"add": add})[0]
with contextlib.redirect_stdout(io.StringIO()):
    res = doctest.DocTestRunner().run(t)
print(res.attempted, res.failed)
  1. A

    2 1

  2. B

    2 0

  3. C

    1 1

  4. D

    2 2

正解と解説を見る

正解:A

doctest は、docstring の >>> の例を実行し、出力が期待どおりかを調べる。実行した数と失敗した数が結果として返る。

順実行する行実行後の変数
1`import doctest, io, contextlib`—
2`def add(a, b):`—
3`t = doctest.DocTestFinder().find(add, "add", …`—
4`with contextlib.redirect_stdout(io.StringIO()…`—
5`res = doctest.DocTestRunner().run(t)`res = TestResults(failed=1, attempted=2)
6└ `return a + b`(2回)a = 2, b = 2
7`with contextlib.redirect_stdout(io.StringIO()…`—
8`print(res.attempted, res.failed)`res = TestResults(failed=1, attempted=2)
結果実際の出力2 1

学習のポイント:doctest.testmod() でモジュール全体を調べる。

この問題を演習で解く →

問題一覧へ

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