Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question]: RuntimeError: Cannot run the event loop while another loop is running #1339

Closed
baiyyee opened this issue Jun 1, 2022 · 3 comments

Comments

@baiyyee
Copy link

baiyyee commented Jun 1, 2022

Your question

When trying to do UI automtion with pytest-asyncio and pytest-playwright, I got exception like: RuntimeError: Cannot run the event loop while another loop is running

Code structure:

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

Detail exception as below:

image

@mxschmitt
Copy link
Member

pytest-playwright only exposes sync bindings, thats why it's not compatible with the async version of Playwright.

See this feature request to also provide async bindings: microsoft/playwright-pytest#74

@nathanielobrown
Copy link

I'm finding this an issue for a slightly different reason. Some of my tests are async but most are not, and none of the tests that use Playwright are async. Unfortunately, the tests that use Playwright cause an event loop to be opened for the remainder of the session as a result of the browser fixture with session scope. This then conflicts with my async tests trying to open a new event loop, causing the exception RuntimeError: Cannot run the event loop while another loop is running. I need asyncio for some of my other tests, so this is an issue.

I guess I can override the browser fixture so that it is module scope or even more granular, but do you have any other ideas or advice?

@feluelle
Copy link

You can use nest-asyncio to patch asyncio to use nested event loops:

import nest_asyncio
nest_asyncio.apply(browser._loop)

should do the job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants