Featured image of post Advanced Fixture Techniques in Playwright

Advanced Fixture Techniques in Playwright

In this article we will sort out and discuss some advanced applications of built-in fixtures in Playwright, to help us use `Playwright` better

Advanced Fixture Techniques in Playwright

As the most promising automated testing tool today, Playwright has fully absorbed the strengths of many other frameworks. A key one is borrowing the fixture advantages of pytest; its JavaScript and .NET versions also provide fixture support. Of course, its Python version also continues to include a rich set of built-in fixtures.

In this article we will sort out and discuss some advanced applications of built-in fixtures in Playwright, to help us use Playwright better.

Overview of Playwright Built-in Fixtures

The Playwright Python version includes the following core built-in fixtures:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# basic fixtures
@pytest.fixture
def browser():  # browser instance
    pass

@pytest.fixture
def context():  # browser context
    pass

@pytest.fixture
def page():  # page instance
    pass

@pytest.fixture
def playwright():  # Playwright instance
    pass

# configuration fixtures
@pytest.fixture
def browser_name():  # browser name
    pass

@pytest.fixture
def browser_channel():  # browser channel
    pass

@pytest.fixture
def is_mobile():  # whether it is a mobile device
    pass

@pytest.fixture
def device_name():  # device name
    pass

@pytest.fixture
def viewport_size():  # viewport size
    pass

# API fixtures
@pytest.fixture
def request():  # API request context
    pass

Advanced Usage of browser Fixtures

Multi-browser Parallel Testing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# test_browsers.py
import pytest
from playwright.sync_api import Browser, Page

@pytest.fixture(params=["chromium", "firefox", "webkit"])
def cross_browser_page(request, playwright) -> Page:
    """Cross-browser testing fixture"""
    if request.param == "chromium":
        browser = playwright.chromium.launch(headless=True)
    elif request.param == "firefox":
        browser = playwright.firefox.launch(headless=True)
    else:
        browser = playwright.webkit.launch(headless=True)
    
    context = browser.new_context()
    page = context.new_page()
    
    yield page
    
    page.close()
    context.close()
    browser.close()

def test_cross_browser_compatibility(cross_browser_page):
    """Cross-browser compatibility test"""
    cross_browser_page.goto("http://localhost:8080")
    assert cross_browser_page.title() == "Test Page"
    assert cross_browser_page.locator("h1").text_content() == "Test Page"

Advanced Browser Context Configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# test_context.py
@pytest.fixture
def stealth_context(browser):
    """Anti-detection browser context"""
    context = browser.new_context(
        viewport={"width": 1920, "height": 1080},
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        locale="en-US",
        timezone_id="America/New_York",
        geolocation={"longitude": -73.935242, "latitude": 40.730610},
        permissions=["geolocation", "notifications"],
        extra_http_headers={
            "Accept-Language": "en-US,en;q=0.9"
        },
        ignore_https_errors=True,
        java_script_enabled=True
    )
    
    # inject anti-detection script
    context.add_init_script("""
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        });
    """)
    
    yield context
    
    context.close()

@pytest.fixture
def stealth_page(stealth_context):
    """Anti-detection page"""
    page = stealth_context.new_page()
    yield page
    page.close()

def test_stealth_browser(stealth_page):
    """Test anti-detection browser"""
    stealth_page.goto("http://localhost:8080")
    
    # check whether the webdriver attribute is hidden
    is_webdriver = stealth_page.evaluate("() => navigator.webdriver")
    assert is_webdriver is None
    
    # check the user agent
    user_agent = stealth_page.evaluate("() => navigator.userAgent")
    assert "Windows NT 10.0" in user_agent

Browser Performance Monitoring

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# test_performance.py
@pytest.fixture
def performance_page(context):
    """Performance monitoring page"""
    page = context.new_context().new_page()
    
    # enable performance monitoring
    metrics = []
    
    def on_metrics(metrics_data):
        metrics.append(metrics_data)
    
    page.on("metrics", on_metrics)
    
    yield page
    
    # output performance metrics
    if metrics:
        print(f"Page performance metrics: {metrics[-1]}")
    
    page.close()

def test_page_performance(performance_page):
    """Page performance test"""
    performance_page.goto("http://localhost:8080")
    
    # wait for the page to finish loading
    performance_page.wait_for_load_state("networkidle")
    
    # get performance metrics
    metrics = performance_page.evaluate("""
        () => ({
            timing: window.performance.timing,
            memory: window.performance.memory,
            navigation: window.performance.navigation
        })
    """)
    
    # calculate page load time
    load_time = metrics['timing']['loadEventEnd'] - metrics['timing']['navigationStart']
    print(f"Page load time: {load_time}ms")
    
    # verify page load time is within a reasonable range
    assert load_time < 5000  # less than 5 seconds

Advanced Usage of page Fixtures

Smart Wait Strategy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# test_smart_wait.py
@pytest.fixture
def smart_wait_page(context):
    """Smart wait page"""
    page = context.new_page()
    
    # set default timeout
    page.set_default_timeout(10000)
    page.set_default_navigation_timeout(30000)
    
    # custom wait strategy
    original_wait_for_selector = page.wait_for_selector
    
    def enhanced_wait_for_selector(selector, **kwargs):
        """Enhanced wait-for-selector method"""
        try:
            # first try a fast lookup
            element = page.query_selector(selector)
            if element and element.is_visible():
                return element
            
            # if not found, use the original method to wait
            return original_wait_for_selector(selector, **kwargs)
        except Exception as e:
            print(f"Waiting for selector {selector} failed: {e}")
            raise
    
    page.wait_for_selector = enhanced_wait_for_selector
    
    yield page
    page.close()

def test_smart_waiting(smart_wait_page):
    """Test smart waiting"""
    smart_wait_page.goto("http://localhost:8080")
    
    # use the enhanced wait method
    header = smart_wait_page.wait_for_selector("h1")
    assert header.is_visible()
    assert header.text_content() == "Test Page"

Network Interception and Mocking

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# test_network_mock.py
@pytest.fixture
def network_mock_page(context):
    """Network mocking page"""
    page = context.new_page()
    
    # intercept all network requests
    def handle_request(request: Request):
        if "localhost:8080/api" in request.url:
            # mock API response
            if "/api/user" in request.url:
                request.respond({
                    "status": 200,
                    "headers": {"Content-Type": "application/json"},
                    "body": '{"status": "success", "data": {"id": 1, "name": "Mock User", "email": "mock@example.com"}}'
                })
            else:
                request.continue_()
        else:
            request.continue_()
    
    page.route("**/*", handle_request)
    
    yield page
    page.close()

def test_network_mocking(network_mock_page):
    """Test network mocking"""
    network_mock_page.goto("http://localhost:8080")
    
    # create a test page containing an API call
    html_content = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Mock Test</title>
    </head>
    <body>
        <button id="fetch-btn">Fetch User</button>
        <div id="result"></div>
        <script>
            document.getElementById('fetch-btn').addEventListener('click', async () => {
                try {
                    const response = await fetch('http://localhost:8080/api/user');
                    const data = await response.json();
                    document.getElementById('result').innerHTML = 
                        `<p>Name: ${data.data.name}</p><p>Email: ${data.data.email}</p>`;
                } catch (error) {
                    document.getElementById('result').innerText = 'Error: ' + error.message;
                }
            });
        </script>
    </body>
    </html>
    """
    
    network_mock_page.set_content(html_content)
    
    # click the button to trigger the API call
    network_mock_page.click("#fetch-btn")
    
    # wait for the result to display
    result = network_mock_page.locator("#result")
    result.wait_for(state="visible")
    
    # verify the result
    assert "Mock User" in result.text_content()
    assert "mock@example.com" in result.text_content()

Page Screenshot and Video Recording

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# test_recording.py
import os
import time

@pytest.fixture
def recording_page(context):
    """Recording page"""
    # create the results directory
    os.makedirs("test-results/screenshots", exist_ok=True)
    os.makedirs("test-results/videos", exist_ok=True)
    
    context = context.new_context(
        record_video_dir="test-results/videos/",
        record_video_size={"width": 1280, "height": 720}
    )
    
    page = context.new_page()
    
    yield page
    
    # take a screenshot when the test ends
    timestamp = int(time.time())
    page.screenshot(path=f"test-results/screenshots/test_{timestamp}.png")
    
    page.close()
    context.close()

@pytest.fixture
def screenshot_on_failure_page(context):
    """Page that takes a screenshot on failure"""
    page = context.new_page()
    
    yield page
    
    # check whether the test failed
    if hasattr(page, '_test_failed') and page._test_failed:
        timestamp = int(time.time())
        page.screenshot(path=f"test-results/screenshots/failure_{timestamp}.png")
    
    page.close()

def test_recording(recording_page):
    """Test the recording feature"""
    recording_page.goto("http://localhost:8080")
    
    # perform some actions
    recording_page.click("h1")
    recording_page.wait_for_timeout(1000)
    
    # verify page content
    assert recording_page.title() == "Test Page"

def test_screenshot_on_failure(screenshot_on_failure_page):
    """Test screenshot on failure"""
    # mark the test as failed (for demonstration only)
    screenshot_on_failure_page._test_failed = True
    
    screenshot_on_failure_page.goto("http://localhost:8080")
    
    # this assertion will fail, triggering the screenshot
    assert False, "This test is designed to fail to demonstrate screenshot on failure"

Advanced Usage of device and viewport Fixtures

Responsive Testing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# test_responsive.py
@pytest.fixture(params=[
    {"width": 1920, "height": 1080, "name": "Desktop"},
    {"width": 768, "height": 1024, "name": "Tablet"},
    {"width": 375, "height": 667, "name": "Mobile"}
])
def responsive_page(request, browser):
    """Responsive testing page"""
    viewport = request.param
    context = browser.new_context(viewport=viewport)
    page = context.new_page()
    
    # add viewport info to the page
    page._viewport_info = viewport
    
    yield page
    
    page.close()
    context.close()

def test_responsive_design(responsive_page):
    """Responsive design test"""
    responsive_page.goto("http://localhost:8080")
    
    viewport = responsive_page._viewport_info
    
    # perform different verifications based on viewport size
    if viewport["name"] == "Desktop":
        # desktop verification
        assert responsive_page.viewport_size["width"] == 1920
        assert responsive_page.viewport_size["height"] == 1080
    elif viewport["name"] == "Tablet":
        # tablet verification
        assert responsive_page.viewport_size["width"] == 768
        assert responsive_page.viewport_size["height"] == 1024
    elif viewport["name"] == "Mobile":
        # mobile verification
        assert responsive_page.viewport_size["width"] == 375
        assert responsive_page.viewport_size["height"] == 667

Device Simulation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# test_device_simulation.py
@pytest.fixture(params=["iPhone 12", "iPad Pro", "Pixel 5"])
def device_page(request, playwright):
    """Device simulation page"""
    device = playwright.devices[request.param]
    
    browser = playwright.chromium.launch(headless=True)
    context = browser.new_context(**device)
    page = context.new_page()
    
    # add device information
    page._device_info = device
    
    yield page
    
    page.close()
    context.close()
    browser.close()

def test_device_simulation(device_page):
    """Device simulation test"""
    device_page.goto("http://localhost:8080")
    
    device = device_page._device_info
    
    # verify the user agent
    user_agent = device_page.evaluate("() => navigator.userAgent")
    assert device["user_agent"] in user_agent
    
    # verify viewport size
    viewport = device_page.viewport_size
    assert viewport["width"] == device["viewport"]["width"]
    assert viewport["height"] == device["viewport"]["height"]
    
    # verify device pixel ratio
    device_pixel_ratio = device_page.evaluate("() => window.devicePixelRatio")
    assert device_pixel_ratio == device["device_scale_factor"]

Advanced Usage of API Fixtures

API Test Authentication

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# test_api_auth.py
@pytest.fixture
def authenticated_api_context(playwright):
    """Authenticated API context"""
    api_context = playwright.request.new_context()
    
    # log in to get the token
    login_response = api_context.post("http://localhost:8080/api/login", {
        "username": "testuser",
        "password": "testpass"
    })
    
    assert login_response.status == 200
    token = login_response.json()["token"]
    
    # set the authorization header
    api_context.set_extra_http_headers({
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    })
    
    yield api_context
    
    api_context.dispose()

def test_authenticated_api(authenticated_api_context):
    """Authenticated API test"""
    response = authenticated_api_context.get("http://localhost:8080/api/user")
    assert response.status == 200
    
    user_data = response.json()
    assert user_data["name"] == "Test User"
    assert user_data["email"] == "test@example.com"

API Response Validation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# test_api_validation.py
@pytest.fixture
def api_validator():
    """API response validator"""
    def validate_schema(response, schema):
        """Validate the response schema"""
        data = response.json()
        
        def validate_object(obj, schema_def):
            for key, expected_type in schema_def.items():
                if key not in obj:
                    raise AssertionError(f"Missing key: {key}")
                
                if isinstance(expected_type, dict):
                    if not isinstance(obj[key], dict):
                        raise AssertionError(f"Expected dict for key: {key}")
                    validate_object(obj[key], expected_type)
                elif not isinstance(obj[key], expected_type):
                    raise AssertionError(f"Expected type {expected_type} for key: {key}, got {type(obj[key])}")
        
        validate_object(data, schema)
        return True
    
    return validate_schema

def test_api_schema_validation(authenticated_api_context, api_validator):
    """API schema validation test"""
    response = authenticated_api_context.get("http://localhost:8080/api/user")
    
    user_schema = {
        "id": int,
        "name": str,
        "email": str,
    }
    
    assert api_validator(response, user_schema)

Combined Application

A Complete Test Environment

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# test_complete_environment.py
@pytest.fixture
def complete_test_environment(playwright):
    """Complete test environment"""
    # launch the browser
    browser = playwright.chromium.launch(headless=True)
    
    # create the context
    context = browser.new_context(
        viewport={"width": 1920, "height": 1080},
        locale="en-US",
        timezone_id="America/New_York",
        permissions=["geolocation", "notifications"]
    )
    
    # create the page
    page = context.new_page()
    
    # create the API context
    api_context = playwright.request.new_context({
        "base_url": "http://localhost:8080",
        "extra_http_headers": {
            "Content-Type": "application/json"
        }
    })
    
    # set up network interception
    def handle_route(route: Route):
        if "localhost:8080/api" in route.request.url:
            # log the API call
            print(f"API Call: {route.request.method} {route.request.url}")
        route.continue_()
    
    page.route("**/*", handle_route)
    
    # set up performance monitoring
    performance_data = []
    
    def handle_metrics(metrics):
        performance_data.append(metrics)
    
    page.on("metrics", handle_metrics)
    
    # create the test toolset
    test_tools = {
        "page": page,
        "context": context,
        "browser": browser,
        "api_context": api_context,
        "performance_data": performance_data,
        
        # utility methods
        "login": lambda username, password: (
            page.goto("http://localhost:8080"),
            page.fill("#username", username),
            page.fill("#password", password),
            page.click("#login-button"),
            page.wait_for_url("http://localhost:8080/dashboard")
        ),
        
        "screenshot_on_failure": lambda: page.screenshot(
            path=f"test-results/screenshots/failure_{int(time.time())}.png"
        ),
        
        "get_performance_metrics": lambda: performance_data[-1] if performance_data else None
    }
    
    yield test_tools
    
    # cleanup
    page.close()
    context.close()
    browser.close()
    api_context.dispose()

def test_complete_workflow(complete_test_environment):
    """Complete workflow test"""
    tools = complete_test_environment
    
    # create a login form
    tools["page"].set_content("""
    <!DOCTYPE html>
    <html>
    <head><title>Login</title></head>
    <body>
        <form id="login-form">
            <input type="text" id="username" placeholder="Username">
            <input type="password" id="password" placeholder="Password">
            <button type="submit" id="login-button">Login</button>
        </form>
        <script>
            document.getElementById('login-form').addEventListener('submit', async (e) => {
                e.preventDefault();
                const username = document.getElementById('username').value;
                const password = document.getElementById('password').value;
                
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({username, password})
                });
                
                if (response.ok) {
                    window.location.href = '/dashboard';
                }
            });
        </script>
    </body>
    </html>
    """)
    
    # log in
    tools["login"]("testuser", "testpass")
    
    # verify login succeeded
    assert tools["page"].url == "http://localhost:8080/dashboard"
    
    # verify user info is displayed
    user_info = tools["page"].locator("#user-info")
    assert user_info.is_visible()
    assert "Test User" in user_info.text_content()
    assert "test@example.com" in user_info.text_content()
    
    # get performance metrics
    metrics = tools["get_performance_metrics"]()
    if metrics:
        print(f"Page performance metrics: {metrics}")

Test Data Management

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
# test_data_management.py
import time

@pytest.fixture
def test_data_manager():
    """Test data manager"""
    class DataManager:
        def __init__(self):
            self.data = {}
        
        def create_user(self, **kwargs):
            """Create a test user"""
            user_data = {
                "username": f"testuser_{int(time.time())}",
                "email": f"test_{int(time.time())}@example.com",
                "password": "TestPassword123!",
                **kwargs
            }
            self.data["user"] = user_data
            return user_data
        
        def create_product(self, **kwargs):
            """Create a test product"""
            product_data = {
                "name": f"Test Product {int(time.time())}",
                "price": 99.99,
                "description": "Test product description",
                **kwargs
            }
            self.data["product"] = product_data
            return product_data
        
        def get_data(self, key):
            """Get test data"""
            return self.data.get(key)
        
        def cleanup(self):
            """Clean up test data"""
            self.data.clear()
    
    manager = DataManager()
    yield manager
    manager.cleanup()

@pytest.fixture
def data_driven_test_page(browser, test_data_manager):
    """Data-driven test page"""
    context = browser.new_context()
    page = context.new_page()
    
    # create test data
    test_user = test_data_manager.create_user()
    test_product = test_data_manager.create_product()
    
    # inject test data into the page
    page._test_data = {
        "user": test_user,
        "product": test_product
    }
    
    yield page
    
    page.close()
    context.close()

def test_data_driven_workflow(data_driven_test_page):
    """Data-driven workflow test"""
    page = data_driven_test_page
    test_data = page._test_data
    
    # create a registration form
    page.set_content(f"""
    <!DOCTYPE html>
    <html>
    <head><title>Register</title></head>
    <body>
        <form id="register-form">
            <input type="text" id="username" placeholder="Username">
            <input type="email" id="email" placeholder="Email">
            <input type="password" id="password" placeholder="Password">
            <button type="submit" id="register-button">Register</button>
        </form>
        <div id="welcome-message" style="display:none;"></div>
        <script>
            document.getElementById('register-form').addEventListener('submit', (e) => {{
                e.preventDefault();
                const username = document.getElementById('username').value;
                const email = document.getElementById('email').value;
                
                document.getElementById('welcome-message').style.display = 'block';
                document.getElementById('welcome-message').textContent = `Welcome ${{username}}!`;
            }});
        </script>
    </body>
    </html>
    """)
    
    # test with the test data
    page.goto("about:blank")
    page.fill("#username", test_data["user"]["username"])
    page.fill("#email", test_data["user"]["email"])
    page.fill("#password", test_data["user"]["password"])
    page.click("#register-button")
    
    # verify registration succeeded
    welcome_message = page.locator("#welcome-message")
    assert welcome_message.is_visible()
    assert test_data["user"]["username"] in welcome_message.text_content()

Performance Optimization

Context Reuse

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# test_context_reuse.py
@pytest.fixture(scope="session")
def shared_browser(playwright):
    """Session-scoped shared browser"""
    browser = playwright.chromium.launch(headless=True)
    yield browser
    browser.close()

@pytest.fixture(scope="module")
def shared_context(shared_browser):
    """Module-scoped shared context"""
    context = shared_browser.new_context()
    yield context
    context.close()

@pytest.fixture
def optimized_page(shared_context):
    """Optimized page fixture"""
    page = shared_context.new_page()
    
    # preload common resources
    page.goto("about:blank")
    page.evaluate("""
        () => {
            // preload common libraries
            const preload = (src) => {
                const link = document.createElement('link');
                link.rel = 'preload';
                link.as = 'script';
                link.href = src;
                document.head.appendChild(link);
            };
            
            // preload common scripts
            preload('http://localhost:8080/common.js');
        }
    """)
    
    yield page
    page.close()

def test_context_reuse(optimized_page):
    """Test context reuse"""
    optimized_page.goto("http://localhost:8080")
    assert optimized_page.title() == "Test Page"

Parallel Test Optimization

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# test_parallel_optimization.py
@pytest.fixture
def parallel_test_page(browser):
    """Parallel test optimization page"""
    context = browser.new_context(
        # reduce resource consumption
        java_script_enabled=True,
        ignore_https_errors=True,
        bypass_csp=True
    )
    
    page = context.new_page()
    
    # set fast timeouts
    page.set_default_timeout(5000)
    page.set_default_navigation_timeout(10000)
    
    # disable unnecessary features
    def block_resources(route):
        if route.request.resource_type in ["image", "stylesheet", "font"]:
            route.abort()
        else:
            route.continue_()
    
    page.route("**/*", block_resources)
    
    yield page
    
    page.close()
    context.close()

@pytest.mark.parametrize("test_case", ["case1", "case2", "case3"])
def test_parallel_execution(parallel_test_page, test_case):
    """Parallel execution test"""
    parallel_test_page.goto(f"http://localhost:8080?test={test_case}")
    
    # quick verification
    assert parallel_test_page.locator("h1").is_visible()
    assert parallel_test_page.title() == "Test Page"

Conclusion

The above is a summary of some advanced techniques for using Fixtures in the Playwright Python version. Reply playwright fixture in our official account to get the source code above

9. Summary of Best Practices

9.1 Fixture Design Principles

  1. Single responsibility: Each fixture is responsible for only one function
  2. Reasonable scope: Choose an appropriate scope based on the resource lifecycle
  3. Resource cleanup: Ensure resources are properly cleaned up when the fixture ends
  4. Error handling: Add appropriate error handling in the fixture

9.2 Performance Optimization Suggestions

  1. Reuse resources: Use session or module scope to reuse browsers and contexts
  2. Parallel execution: Design fixtures that support parallel execution
  3. Resource management: Manage memory and network resources reasonably
  4. Timeout settings: Set reasonable timeouts based on test needs

9.3 Maintainability Suggestions

  1. Documentation: Add docstrings to complex fixtures
  2. Type hints: Use type hints to improve code readability
  3. Configuration: Extract hard-coded values into configuration parameters
  4. Modularity: Organize related functionality into modules

Through these fully executable examples, you can gain an in-depth understanding of the advanced application techniques of Playwright Python fixtures, and apply these patterns in real projects to build efficient, reliable test frameworks.

Built with Hugo
Theme Stack designed by Jimmy