Android Automation
Relevant source files
The following files were used as context for generating this wiki page:
Playwright provides capabilities for automating and testing web applications on Android devices. This is achieved by controlling a browser (specifically Chromium) running on a connected Android device or emulator. The framework leverages the Android Debug Bridge (ADB) to communicate with the device, install necessary components, and manage the browser lifecycle.
The architecture follows Playwright's standard client-server model. A Playwright script communicates with the Playwright server, which in turn uses ADB to forward commands to the Android device. This allows for a rich set of interactions, including launching browsers with specific contexts, navigating pages, executing scripts, and capturing screenshots and traces, all within the Android environment.
Architecture
The Android automation feature in Playwright operates through a layered architecture, with the Playwright test script at the top and the Android device at the bottom. The core components are the Playwright client, the Playwright server, and the Android Debug Bridge (ADB).
This diagram illustrates the communication flow from the test script to the browser running on the Android device.
Sources: packages/playwright-core/src/server/android/android.ts, packages/playwright-core/src/client/android.ts
Configuration
To enable Android testing, a specific project configuration is required in playwright.config.ts. This involves setting environment variables and defining a project with Android-specific use options.
A critical environment variable is PWPAGE_IMPL, which must be set to 'android'.
Sources: tests/android/playwright.config.ts:20
Project Configuration
An Android project in the configuration file specifies the browserName and a loopback address for the server to communicate with the host machine from within the emulator.
// tests/android/playwright.config.ts:36-45
config.projects!.push({
name: 'android-native',
use: {
loopback: '10.0.2.2',
browserName: 'chromium',
},
snapshotPathTemplate: '{testDir}/{testFileDir}/{testFileName}-snapshots/{arg}-android{ext}',
testDir: path.join(testDir, 'android'),
metadata,
});
| Option | Type | Description | Source |
|---|---|---|---|
name | string | A unique name for the project, e.g., 'android-native'. | tests/android/playwright.config.ts:37 |
use.loopback | string | The IP address for the emulator to connect back to the host machine. Typically '10.0.2.2'. | tests/android/playwright.config.ts:39 |
use.browserName | string | Must be set to 'chromium' for Android testing. | tests/android/playwright.config.ts:40 |
snapshotPathTemplate | string | A template for snapshot paths, often customized to include an 'android' suffix to differentiate from desktop snapshots. | tests/android/playwright.config.ts:42 |
testDir | string | The directory containing the tests for this project. | tests/android/playwright.config.ts:43 |
Core Classes
The primary interface for interacting with an Android device is the AndroidDevice class, which exists on both the client and server side.
Class Diagram
This diagram shows the relationship between the main classes involved in Android automation.
AndroidDevice
This class represents a connected Android device and is the main entry point for automation.
| Method | Description | Source |
|---|---|---|
model() | Returns the model name of the Android device. | tests/android/browser.spec.ts:23-25 |
launchBrowser(options) | Launches a Chromium browser instance on the device with specified context options. | tests/android/browser.spec.ts:27-31 |
shell(command) | Executes a shell command on the device. | packages/playwright-core/src/server/android/android.ts:223-225 |
close() | Disconnects from the device. | packages/playwright-core/src/server/android/android.ts:133-136 |
newCDPSession(page) | Creates a new Chrome DevTools Protocol session attached to the specified page. | tests/android/browser.spec.ts:100-105 |
Testing and Usage
Tests for Android are written using the standard Playwright Test API, with the androidDevice fixture providing the entry point.
Test Execution Flow
A typical test involves launching a browser on the device, creating a page, performing actions, and then cleaning up.
This sequence diagram shows the object interactions during a simple test case.
Sources: tests/android/browser.spec.ts
Common Operations
The test specifications demonstrate a wide range of capabilities available for Android testing.
Launching Browser with Options
You can launch the browser with various context options, similar to desktop browser testing.
// tests/android/browser.spec.ts:107-124
test('should be able to pass context options', async ({ androidDevice, httpsServer }) => {
const context = await androidDevice.launchBrowser({
colorScheme: 'dark',
geolocation: { longitude: 10, latitude: 10 },
permissions: ['geolocation'],
ignoreHTTPSErrors: true,
baseURL: httpsServer.PREFIX,
});
const [page] = context.pages();
// ... assertions
await context.close();
});
Taking Screenshots
Both page and full-page screenshots are supported.
// tests/android/browser.spec.ts:79-81
const screenshot = await page.screenshot({ fullPage: false, scale: 'css' });
const fullPageScreenshot = await page.screenshot({ fullPage: true, scale: 'css' });
Recording HAR files
Network activity can be recorded into a HAR file for analysis.
// tests/android/browser.spec.ts:126-136
test('should record har', async ({ androidDevice }) => {
const harPath = test.info().outputPath('test.har');
const context = await androidDevice.launchBrowser({
recordHar: { path: harPath }
});
const [page] = context.pages();
await page.goto('data:text/html,<title>Hello</title>');
await page.waitForLoadState('domcontentloaded');
await context.close();
const log = JSON.parse(fs.readFileSync(harPath).toString())['log'];
expect(log.pages[0].title).toBe('Hello');
});
Device Management
For CI environments, Playwright uses scripts to manage Android Virtual Devices (AVDs). The avd_start.sh script is an example of how an emulator can be started, prepared, and made ready for tests. It handles waiting for the device to boot and ensuring the package manager is available.
Key steps in the script include:
- Starting the emulator with specific options (
-no-audio,-no-window, etc.). - Waiting for the device to fully boot by checking the
sys.boot_completedproperty. - Waiting for the package manager to be ready.
Sources: utils/avd_start.sh
Summary
Playwright's Android automation extends its powerful testing capabilities to the mobile web. By leveraging ADB and a client-server architecture, it provides a seamless experience for developers to write and run cross-browser tests on Android. The feature is well-integrated into the existing Playwright ecosystem, supporting configuration via playwright.config.ts, standard test fixtures, and advanced functionalities like tracing, HAR recording, and screenshot testing.