我正在尝试为 asyncio 函数编写一个 pytest 测试用例,该函数确实读取输出流(stderr/stdout)并修改行。我要测试的函数(再次被调用 inside asyncio.gather
)如下所示:
import asyncio
async def watch(stream):
while True:
lines = await stream.read(2**16)
if not lines or lines == "":
break
lines = lines.strip().split("\n")
for line in lines:
print(f'myPrefix-{line}')
我写的pytest测试用例如下:
import asyncio
from io import StringIO
import pytest
@pytest.fixture(autouse=True)
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.mark.asyncio
async def test_watch(event_loop):
expected_outcome = "myPrefix-This is stdout"
def write_something():
print("This is stdout")
with patch("sys.stdout", new=StringIO()) as mock_stdout:
write_something()
output = await watch(mock_stdout.getvalue())
assert output.return_value == expected_outcome
但是,当我执行这个 pytest 时,我遇到了AttributeError: 'str' object has no attribute 'read'
. 如何在处理 stdout/stderr 流时测试 asyncio 协程?