When I run the following doctest in Mac terminal
>>> 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.
I get the following output with a "33" at the end, which makes this test fail. Any idea how to correct this?
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.
sys.stdout.write
is a function that returns the amount of characters that was written. Prior to returning, it writes the argument to the console. So when you call sys.stdout.write("This text contains weird spacing.")
the string is written to the console, and then the length of the string (33
) is returned. That is why doctest is getting This text contains weird spacing.33
.
I suggest you use the print
method instead:
>>> print("This text contains weird spacing.")
... # doctest: +NORMALIZE_WHITESPACE
This text contains weird spacing.
If you must use sys.stdout.write
you can capture the returned value, that way it would be ignored by doctest
. Like this:
>>> ln = sys.stdout.write("This text contains weird spacing.")
... # doctest: +NORMALIZE_WHITESPACE
This text contains weird spacing.