我想把异步和pytest结合起来。
以下是我想做的事:
我喜欢这样编写测试代码:
def test_add(svr_fixture):
await asyncio.sleep(100)
assert m.add(1, 2) == 3 # I like the readability of this and want to restore it我试图用pytest-asyncio (https://pypi.python.org/pypi/pytest-asyncio)编写这个夹具,但是我想不出如何做到这一点。
我想出的这个测试(虽然有效,但看起来很笨拙,掩盖了测试的意图):
def test_add():
async def do_it():
await asyncio.sleep(100)
return m.add(1, 2)
loop = asyncio.get_event_loop()
coro = loop.create_server(server.ServerProtocol, '127.0.0.1', 8023)
asyncio.async(coro)
res = loop.run_until_complete(do_it())
assert res == 3任何关于如何将服务器代码解压缩到固定设备中的帮助,如指向文档或示例的链接,都将不胜感激。
我不认为完整的服务器代码是必要的(但它在这里:https://stackoverflow.com/a/48277838/570293)
发布于 2018-01-22 09:09:41
正如我在我的问题中指出的,我不希望异步的东西膨胀我的测试案例。到目前为止,我能找到的唯一简单的工作解决方案是使用多处理。我知道process.terminate()不是结束异步循环的“最佳方式”,但至少它是可靠的。
# -*- coding: utf-8 -*-
import time
from multiprocessing import Process
import pytest
from my_server import server
@pytest.fixture
def fake_server():
p = Process(target=server.run, args=())
p.start()
yield
p.terminate()
def test_add2(fake_server):
time.sleep(30)
assert m.add(1, 2) == 3https://stackoverflow.com/questions/48286838
复制相似问题