在Mac终端上的doctest中运行+ NORMALIZE WHITESPACE时出错

时间:2015-05-19 22:34:44

标签: python python-3.x doctest

当我在Mac终端中运行以下doctest

>>> import sys
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
... # doctest: +NORMALIZE_WHITESPACE
[1, 2, 3,
4, 5, 6,
7, 8, 9]
>>> sys.stdout.write("This text contains weird spacing.")
... # doctest: +NORMALIZE_WHITESPACE
This text contains weird spacing.

我使用" 33"得到以下输出。最后,这使得这个测试失败了。 知道怎么纠正这个吗?

File "test2.txt", line 8, in test2.txt
Failed example:
    sys.stdout.write("This text contains weird spacing.")
    # doctest: +NORMALIZE_WHITESPACE
Expected:
    This text contains weird spacing.
Got:
    This text contains weird spacing.33
**********************************************************************
1 items had failures:
   1 of   3 in test2.txt
***Test Failed*** 1 failures.

1 个答案:

答案 0 :(得分:2)

sys.stdout.write是一个返回已写入字符数的函数。 在返回之前,它将参数写入控制台。因此,当您调用sys.stdout.write("This text contains weird spacing.")时,字符串将写入控制台,然后返回字符串的长度(33)。这就是doctest获得This text contains weird spacing.33的原因。

我建议您改用print方法:

>>> print("This text contains weird spacing.")
... # doctest: +NORMALIZE_WHITESPACE
This text contains weird spacing.

如果必须使用sys.stdout.write,则可以捕获返回的值,doctest将忽略该值。像这样:

>>> ln = sys.stdout.write("This text contains weird spacing.")
... # doctest: +NORMALIZE_WHITESPACE
This text contains weird spacing.