microsoft / playwright-pytest

Pytest plugin to write end-to-end browser tests with Playwright.
https://playwright.dev/python/docs/test-runners
Apache License 2.0
425 stars 70 forks source link

Can't use CreateContextCallback in a type hint #244

Closed slafs closed 1 week ago

slafs commented 2 weeks ago

We have a Python project based on pytest and playwright. We wanted to leverage type hints from the beginning and we're using mypy for type checking. When we write a test (or a fixture) that uses one of the playwrights pytest fixtures (like context or page) we can easily type hint that e.g.:

def test_foo(page: Page) -> None:
    assert isinstance(page, Page)

However, we ran into a problem where we can't really type hint the usage of new_context fixture. While trying this:

from playwright.sync_api import BrowserContext
from pytest_playwright.pytest_playwright import CreateContextCallback

def test_foo(new_context: CreateContextCallback) -> None:
    context = new_context()
    assert isinstance(context, BrowserContext)
    context.close()

Mypy screams:

...:2: error: Skipping analyzing "pytest_playwright.pytest_playwright": module is installed, but missing library stubs or py.typed marker  [import-untyped]
...:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports

Used versions:

mypy==1.11.2
mypy-extensions==1.0.0
playwright==1.46.0
pytest-playwright==0.5.1
aspenboy commented 2 weeks ago

From looking at pytest_playwright sources it seems they're using BrowserContext:

@pytest.fixture
def page(context: BrowserContext) -> Generator[Page, None, None]:
    page = context.new_page()
    yield page

Maybe this will help?

slafs commented 2 weeks ago

context fixture is fine. It's the new_context fixture that doesn't "work" for us.

aspenboy commented 2 weeks ago

Sorry, I somehow managed to ignore the fact, that I have outdated pytest-playwright in my setup :(

mxschmitt commented 1 week ago

This should be fixed as part of 0.5.2.