我试图编写一个pytest测试用例,针对一个异步函数,该函数读取输出流(stderr/stdout)并修改行。我要测试的函数(再次在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协程?