Is it possible to write a docstring test for a function that prints out the colored text into the command line? I want to test only the content ignoring the color or to add somehow the information on color into the docstring. In the example below the test has failed, but it should not.
Example
from colorama import Fore
def print_result():
"""Prints out the result.
>>> print_result()
Hello world
"""
print('Hello world')
def print_result_in_color():
"""Prints out the result.
>>> print_result_in_color()
Hello world
"""
print(Fore.GREEN + 'Hello world' + Fore.RESET)
if __name__ == '__main__':
import doctest
doctest.testmod()
Output
Failed example:
print_result_in_color()
Expected:
Hello world
Got:
Hello world
Yes, it is possible to encode the color information into the docstring using wrapper that alters the docstrings.
Below is the example code that passes the test
from colorama import Fore
def wrapper(func): # wrapper func that alters the docstring
func.__doc__ = func.__doc__.format(**{"GREEN": Fore.GREEN, "RESET": Fore.RESET})
return func
def print_result():
"""Prints out the result.
>>> print_result()
Hello world
"""
print("Hello world")
@wrapper
def print_result_in_color():
"""Prints out the result.
>>> print_result_in_color()
{GREEN}Hello world{RESET}
"""
print(Fore.GREEN + "Hello world" + Fore.RESET)
if __name__ == "__main__":
import doctest
doctest.testmod()
Note: You can also look into these answers for a more in-depth view on this