gpt4 book ai didi

python - 如何在pytest中为asyncio代码编写fixture

转载 作者:行者123 更新时间:2023-11-28 19:04:47 25 4
gpt4 key购买 nike

我想将 asyncio 与 pytest 一起使用。

这是我想做的:

  • 在我的测试运行时运行服务器 - 当它运行时停止服务器完成
  • 在一个完美的世界中,我会将服务器实现为固定装置(使用 yield)

我喜欢这样写测试代码:

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 ) 编写 fixture,但不知道该怎么做。

我在这次测试中得出的结论(有效但看起来很笨拙并且掩盖了测试的意图):

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)

最佳答案

就像我在问题中指出的那样,我不希望异步内容使我的测试用例膨胀。到目前为止我能找到的唯一简单的工作解决方案是使用多处理。我知道 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) == 3

关于python - 如何在pytest中为asyncio代码编写fixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com