On python 3.9.6 the following program prints "a" to stdout. I'd expect both print_a
and print_b
to behave the same.
import io
from unittest.mock import patch
import sys
def print_a(file=sys.stdout):
"""
Does not get redirected to the mocked stdout
"""
print("a", file=file)
def print_b():
"""
Does get redirected to the mocked stdout
"""
print("b", file=sys.stdout)
@patch("sys.stdout", new_callablle=io.StringIO)
def test_print(func, mock_stdout):
func()
# Expect no output to stdout
test_print(print_a)
test_print(print_b)
Making the default file=None
and then setting file
conditionally produces the expected result.
import io
from unittest.mock import patch
import sys
def print_a(file=None):
"""
Does get redirected to the mocked stdout
"""
file = file or sys.stdout
print("a", file=file)
def print_b():
"""
Does get redirected to the mocked stdout
"""
print("b", file=sys.stdout)
@patch("sys.stdout", new_callablle=io.StringIO)
def test_print(func, mock_stdout):
func()
# Expect no output to stdout
test_print(print_a)
test_print(print_b)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.