admin管理员组

文章数量:1124157

I'm creating a test suite for E2E tests that validate network requests while navigating and interacting with a website. I'm using Playwright with async and using conftest.py to set up the browser (every test is going to use the browser), but I don't know how to do it in a way that either allows the test methods in a test class use the same browser context so I can keep tests separated, while continuing from the previous test (maintaining login state and current page).

# conftest.py
import pytest
from playwright.async_api import async_playwright

@pytest.fixture(scope='class')
async def setup_browser(request: pytest.FixtureRequest):
    async with async_playwright() as pw:
        browser = await pw.chromium.launch(
            headless=headless,
            args=['--start-maximized', '--start-fullscreen']
        )
        context = await browser.new_context()
        page = await context.new_page()
        yield page
        await browser.close()
# test_request_collector.py
import pytest
from helpers.request_handler import RequestHandler

class TestNetworkRequests:
    @pytest.mark.asyncio
    async def test_capture_network_requests_first_page(self, setup_browser):
        async for page in setup_browser:
            self.page = page
            request_handler = RequestHandler()
            trigger = self.page.goto(";)
            requests = await request_handler.return_requests(self.page, trigger)
            await request_handler.print_requests(requests)
            assert requests is not None

    @pytest.mark.asyncio
    async def test_capture_network_requests_second_page(self, setup_browser):
        async for page in setup_browser:
            self.page = page
            request_handler = RequestHandler()
            trigger = self.page.goto(";)
            requests = await request_handler.return_requests(self.page, trigger)
            await request_handler.print_requests(requests)
            assert requests is not None

本文标签: pythonHow do I use Playwright (with async methods) and Pytest to create E2E testsStack Overflow