Location>code7788 >text

The latest out of the box series - Python+Playwright automated testing - 67 - Simulating mobile browser compatibility testing

Popularity:824 ℃/2024-08-09 08:20:24

1. Introduction

In our daily work, we will encounter the need to use different hardware devices to test the compatibility of the problem, especially now that the cell phone model is basically a new model released by each manufacturer each year, and the screen size of the phone's resolution of a variety of, we basically can not be all the models are used to test the real machine all over again, playwright provides an imitation of the model of the function, we can use the playwright provides the ability to emulate a device. With Playwright, you can test your apps on any browser, or simulate a real device, such as a phone or tablet. Simply configure the device you want to emulate and Playwright will emulate browser behavior such as "userAgent", "screenSize", "viewport screenSize", "viewport", and whether or not "hasTouch" is enabled. You can also simulate "geolocation", "regional settings" and "timezone" for all tests or for specific tests, as well as set "permissions "to show notifications or change the colorScheme.

In today's web development, mobile devices have become one of the main ways users access websites. Therefore, it is crucial to ensure that your website displays correctly and functions properly on mobile devices.Playwright is a powerful automated testing tool that helps developers simulate various mobile devices and perform automated tests. In this article, we will take an in-depth look at how to write code in Python to simulate mobile devices and perform automated testing on mobile.

2. What is mobile device simulation?

Mobile device emulation is the process of simulating the hardware and software characteristics of a mobile device in order to accurately render a website in a desktop browser. This includes simulating the device's screen size, resolution, user agent strings, and more. By simulating mobile devices, developers can more accurately test the performance and user experience of their websites on mobile devices.

3. Simulate cell phone syntax

Documentation address of the official API for the introduction of analog phones:Emulation | Playwright Python

3.1devices

Comes with a device parameter registry to use for selected desktops, tablets and mobile devices. It can be used to simulate device-specific browser behavior, such as user agent, screen size, viewport, and whether touch is enabled. All tests will be run using the specified device parameters.

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    iphone_13 = ['iPhone 13']
    browser = (headless=False)
    context = browser.new_context(
        **iphone_13,
    )
    # context = browser.new_context()
    page = context.new_page()
    ("")
    page.wait_for_timeout(5000)

with sync_playwright() as playwright:
    run(playwright)

2. After running the code, the action of the browser on the computer side (the window interface becomes the window of the cell phone mode). As shown in the figure below:

3.2Viewport

is included in the device, but you can use () to override the viewport in the device and reset it.

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    # iphone_13 = ['iPhone 13']
    browser = (headless=False)
    # context = browser.new_context(
    #     **iphone_13,
    # )
    # page = context.new_page()
    # Create context with given viewport
    context = browser.new_context(
        viewport={'width': 1280, 'height': 1024}
    )
    page = context.new_page()
    # Resize viewport for individual page
    page.set_viewport_size({"width": 1600, "height": 1200})

    # Emulate high-DPI
    context = browser.new_context(
        viewport={'width': 2560, 'height': 1440},
        device_scale_factor=2,
    )

    ("")
    page.wait_for_timeout(5000)

with sync_playwright() as playwright:
    run(playwright)

2. Run the code after the browser action on the computer side. As shown in the figure below:

3.3isMobile

Whether the original viewport markup is considered and touch events are enabled.

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):

    browser = (headless=False)

    context = browser.new_context( is_mobile = False)
    page = context.new_page()
    ("")
    page.wait_for_timeout(5000)

with sync_playwright() as playwright:
    run(playwright)

The official website is written as follows, but Macro reports an error running it:

context = browser.new_context(
  isMobile=false
)

Then Macro went into the method and looked at it, maybe the official documentation has not been updated. As shown in the picture below:

3.4 Setting the language and time zone

1. simulating user area settings and time zones can be set globally for all tests in the configuration and then overridden for specific tests.

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):

    browser = (headless=False)
    context = browser.new_context(
        locale='de-DE',
        timezone_id='Europe/Berlin'
    )
    page = context.new_page()
    ("")
    ()
    page.wait_for_timeout(5000)

with sync_playwright() as playwright:
    run(playwright)

2. After running the code, the browser on the computer side of the action (you can see that some of the contents of the browser has been changed to German). As you can see in the picture below:

3.5 Competence

1. Allow apps to show system notifications.

context = browser.new_context(
  permissions=['notifications'],
)

2. Allow domain (site) specific notifications.

context.grant_permissions(['notifications'], origin='')

3. Revoke all permissions.

context.clear_permissions()

3.6 Setting the geographic location

1. Grant permissions and set the geolocation to a specific area.

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):

    browser = (headless=False)
    context = browser.new_context(
        geolocation={"longitude": 41.890221, "latitude": 12.492348},
        permissions=["geolocation"]
    )
    page = context.new_page()
    ("/")
    ()
    page.wait_for_timeout(5000)

with sync_playwright() as playwright:
    run(playwright)

2. After running the code, the browser on the computer side of the action (we see the location information from "Beijing" to "eli dar"). As you can see in the picture below:

Change the location later:

context.set_geolocation({"longitude": 48.858455, "latitude": 2.294474})

Knockout:Note that you can only change the geolocation of all pages in the context.

3.7 Setting the website display color (dark or light)

Simulates the user. Supported values are 'light', 'dark', and 'no-preference'. You can also simulate media types using page.emulate_media()." colorScheme"

# Create context with dark mode
context = browser.new_context(
  color_scheme='dark' # or 'light'
)

# Create page with dark mode
page = browser.new_page(
  color_scheme='dark' # or 'light'
)

# Change color scheme for the page
page.emulate_media(color_scheme='dark')

# Change media for page
page.emulate_media(media='print')

3.8User Agent

The user agent is included in the device so you will rarely need to change it, however, if you do need to test another user agent, you can override it using this property.userAgent

context = browser.new_context(
  user_agent='My user agent'
)

3.9 Simulating the network offline

The analog network is offline.

context = browser.new_context(
  offline=True
)

3.10 Enabling and Disabling JavaScript

Simulates user scenarios that disable JavaScript.

context = browser.new_context(
  java_script_enabled=False
)

4. Setting the cell phone mode

In fact, this has been mentioned in the front of the device in, but she as the main character of today, Hong here to take out again to explain. Specific steps are as follows:

1. Configure the device to be emulated, we need to configure the device we are using, Playwright will emulate the browser behavior, such as "userAgent", "screenSize", and "viewport" whether "hasTouch" is enabled.

2. It is also possible to simulate for all tests or for specific tests, as well as to set the "geolocation" to show notifications or changes. "locale" "timezone" "permissions" "colorScheme "

Use to provide device parameter registries for selected desktops, tablets, and mobile devices.

4. It can be used to simulate device-specific browser behavior, such as user agent, screen size, viewport, and whether touch is enabled. All tests will be run using the specified device parameters.

Playwright provides a rich API that makes it easy to emulate a variety of mobile devices. Below is an example that demonstrates how to use Playwright to emulate an iPhone X and access a website:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = ()
    context = browser.new_context(
        **['iPhone X']
    )
    page = context.new_page()
    
    ('')

    # Perform automated testing for mobile
    # Your code here

In this example, we use ['iPhone X'] to select the device to emulate. We then create a new browser context on that device and visit the website.

4.1 Execute automated tests for mobile

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = ()
    context = browser.new_context(
        **['iPhone X']
    )
    page = context.new_page()
    
    ('')

    # Testing Responsive Layouts
    # Your code here

    # Testing Interactive Functions
    # Your code here

4.2 Project practice

Macro here is still to Du Niang search "Beijing Macro" as an example of practical demonstration.

4.2.1 Code design

4.2.2 Reference code
# coding=utf-8🔥

# 1. First set the encoding, utf-8 can support Chinese and English, such as the above, generally placed in the first line

# 2. Notes: including record creation time, creator, project name.
'''
Created on 2024-06-17
@author: Beijing, capital of People's *-* businessman
Public No.: Beijing Hong (WeChat search: Beijing Hong, pay attention to Hong, unlock more testing dry goods in advance!)
Project:The latest out of the series of small into the chapter - Python + Playwright automated testing - 67 - simulation of mobile browser testing
'''

# 3. Import module
from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):

    iphone_15 = ['iPhone 13']
    browser = (headless=False)
    context = browser.new_context(
        **iphone_15,
        locale='de-DE',
        timezone_id='Europe/Berlin',
        geolocation={"longitude": 41.890221, "latitude": 12.492348},
        permissions=["geolocation"]
    )
    page = context.new_page()
    ("/")
    ("#index-kw").fill("Beijing Hong")
    ("#index-bn").click()
    ()
    page.wait_for_timeout(5000)

with sync_playwright() as playwright:
    run(playwright)
4.2.3 Running the code

1. Run the code, right click Run 'Test', you can see the console output, as shown below:

2. Run the code after the browser action on the computer side. As shown in the figure below:

4.3 pytest-playwright test case

1. Documentation

# coding=utf-8🔥

# 1. First set the encoding, utf-8 can support Chinese and English, such as the above, generally placed in the first line

# 2. Notes: including record creation time, creator, project name.
'''
Created on 2024-06-17
@author: Beijing, capital of People's *-* businessman
Public No.: Beijing Hong (WeChat search: Beijing Hong, pay attention to Hong, unlock more testing dry goods in advance!)
Project:The latest out of the series of small into the chapter - Python + Playwright automated testing - 67 - simulation of mobile browser testing
'''

import pytest

@(scope="session")
def browser_context_args(browser_context_args, playwright):
    iphone_13 = ['iPhone 13']
    return {
        **browser_context_args,
        **iphone_13,
    }

2. Test cases are written as follows (it is best to write, or run on the error, the author has picked pit).

# coding=utf-8🔥

# 1. First set the encoding, utf-8 can support Chinese and English, such as the above, generally placed in the first line

# 2. Notes: including record creation time, creator, project name.
'''
Created on 2024-06-17
@author: Beijing, capital of People's *-* businessman
Public No.: Beijing Hong (WeChat search: Beijing Hong, pay attention to Hong, unlock more testing dry goods in advance!)
Project:The latest out of the series of small into the chapter - Python + Playwright automated testing - 67 - simulation of mobile browser testing
'''
import pytest
from playwright.sync_api import Page


def test_example(page: Page):

    ("")
    assert () == "Baidu's website"
    page.wait_for_timeout(5000)
    ()


if __name__ == '__main__':
    (["-v", "test_example.py"])

3. Command line to run test cases

pytest --headed --browser chromium .\test_example.py

4. The action of the browser on the computer after running the code (after running, the browser that opens thewebpage, which is a cell phone shaped page modeled after a cell phone browser (the code specifies theiPhone 13)). This is shown in the figure below:

5. Summary

Today I'm going to explain how to use Python and Playwright to simulate a mobile device and perform automated testing on a mobile device.Playwright provides a powerful API that makes simulating a mobile device very easy. But after all, there may still be a difference with the real machine, if you have the conditions or test on the real machine, but now it seems that you can rent a cell phone is not very expensive. There is really no condition to use this method to test. Well, it's not early today, Hong will explain and share here, thank you for your patience to read, I hope it will help you. Oh, right almost forgot in the actual demonstration process, Hong encountered a small problem, is because more familiar with Baidu's search box and search button positioning elements, all Hong on the computer web page according to the previous Baidu home page, to locate the results of the running code, the appearance of the cell phone screen window, but did not perform the test case in accordance with the expected search for "Beijing Hong". The test case of searching "Beijing Hong" was not executed as expected. Tangled half a day suddenly realized that the mobile positioning elements and computer positioning elements may not be the same, the result is this.

5.1 Chrome emulates a mobile view of the location element

1. First visit the Baidu home page, then open the developer tools, click on "toggler device toolbar", as shown in the figure below:

2. Click "toggler device toolbar" to enter the device page, click "Dimensions Responsive", and select the type of mobile device in the drop-down menu, as shown in the following figure:

3. Then refresh the page and start locating the element id lookup, as shown below:

Finds the positioning element of the input box:

Find the positioning element for the "Baidu" button:

At this point, the located element is the one that is found on the cell phone.