当尝试使用pytest-异步和pytest-playwright执行UI自动操作时,我得到了异常,例如: RuntimeError:无法在另一个循环运行时运行事件循环。
代码结构:
ui2/conftest.py
ui2/test_bing.py
ui2/conftest.py
import pytest
import asyncio
@pytest.fixture(scope="session")
def event_loop():
"""重写event_loop"""
loop = asyncio.get_event_loop()
yield loop
loop.close()
ui2/test_bing.py
import pytest
from playwright.async_api import Page
@pytest.mark.asyncio
async def test_bing(page: Page):
await page.goto("http://www.bing.com")
env:
pytest==7.1.2
pytest-asyncio==0.18.3
pytest-playwright==0.3.0
详细异常如下:
发布于 2022-05-31 19:34:54
短期解决方案。
安装nest_asyncio:
pip install nest_asyncio
然后将其添加到主conftest.py文件中:
import nest_asyncio
nest_asyncio.apply()
请在这里找到更详细的解释:
发布于 2022-07-26 01:39:03
因为您是从async_api
导入的,所以听起来像是要编写异步集成测试,希望同时运行。pytest-asyncio
连续运行协同测试,因此您需要使用pytest-asyncio-cooperative
。(如果您希望测试连续运行,则应该使用from playwright.sync_api import Page
。)我建议:
安装pytest-asyncio-cooperative
pip install pytest-asyncio-cooperative
ui2/conftest.py
中移除event_loop
夹具。pytest-asyncio-cooperative
隐式地在同一个事件循环上运行所有测试协同线。使用@pytest.mark.asyncio_cooperative
标记异步测试的
import pytest
from playwright.async_api import Page
@pytest.mark.asyncio_cooperative
async def test_bing(page: Page):
await page.goto("http://www.bing.com")
-p no:asyncio
选项运行测试。pytest-aysncio
与pytest-asyncio-cooperative
不兼容,因此必须禁用或禁用pytest-asyncio-cooperative
。pytest -p no:asyncio
https://stackoverflow.com/questions/72371401
复制相似问题