pytest-dev / pytest-dev/pytest

Make async functions support in pytest hooks

Open
#13,059 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: proposal
Dominant language
Python
Stars
14.5k
Forks
3.4k
Avg merge
2d 9h
Merged PRs (30d)
35

Description

What's the problem this feature will solve?

I'm trying to make scteenshots on test failture.
The ways I found in internet is to make it via pytest_runtest_makereport hook.

Somthing like:

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()

    if rep.when == "call" and rep.failed:
        page = item.funcargs["async_page"]
        full_path = "some_path"
        page.screenshot(path=f"{full_path}")
        logging.debug(f"Screenshot saved: {full_path}")

But I got an error: RuntimeWarning: coroutine 'Page.screenshot' was never awaited

The reason of error is that async_page fixture is async:

import pytest_asyncio
from playwright.async_api import Page, async_playwright
from typing import AsyncGenerator


@pytest_asyncio.fixture
async def async_page() -> AsyncGenerator[Page]:
    async with async_playwright() as playwright:
        browser = await playwright.chromium.launch(headless=False)
        context = await browser.new_context(viewport={"width": 1440, "height": 900})
        page = await context.new_page()

        yield page
Describe the solution you'd like

I'd like to have an option to call async functions in Pytest hook.
Or if there are any solutions already exiss, please tell me)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the pytest_runtest_makereport hook example and the async_page fixture shown in the issue; trace how hook calls are scheduled and how the Playwright coroutine is exposed. Define done as a supported, tested way to invoke async work from pytest hooks, including the failure-screenshot case.

Written by the indexing model from the issue text.

Assessment

Tech stack
playwright, python
Domain
testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.