### Install XDevice and Extension using Python Source: https://github.com/arkui-x/arkxtest/blob/master/xdevice/README.md Installs the XDevice tool and its extension using Python's setup.py script. Ensure you are in the respective installation directories before running the commands. ```python python setup.py install ``` -------------------------------- ### Display Help Information for Test Framework Commands Source: https://github.com/arkui-x/arkxtest/blob/master/xdevice/README.md Retrieves help information for test framework commands. Use 'help ' to get specific details about 'run' or 'list' commands. ```bash help: use help to get information. usage: run: Display a list of supported run command. list: Display a list of supported device and task record. Examples: help run help list ``` -------------------------------- ### Execute Device Operations with XDevice Python API Source: https://context7.com/arkui-x/arkxtest/llms.txt This Python script demonstrates various device operations using the XDevice framework's Device class. It covers connecting to a device, executing shell commands (with and without timeouts), pushing and pulling files, checking file existence, installing and uninstalling HAP packages, rebooting the device, retrieving device properties, and controlling application lifecycle. The example includes error handling for HDC operations and logging. ```python from ohos.environment.device import Device from xdevice import platform_logger from xdevice import HdcError LOG = platform_logger("DeviceOps") def device_operations_example(): """Example of common device operations""" # Get device instance (managed by environment manager) device = Device() device.device_sn = "ABC123456789" try: # Connect to device device.connect() LOG.info(f"Connected to device: {device.device_sn}") # Execute shell command result = device.execute_shell_command("ls -la /data/test") LOG.info(f"Command output: {result}") # Execute with timeout (milliseconds) result = device.execute_shell_command( "pm list packages", timeout=30000 ) # Push file to device local_file = "/home/user/test_data.json" remote_path = "/data/test/test_data.json" device.push_file(local_file, remote_path) LOG.info(f"Pushed {local_file} to {remote_path}") # Pull file from device remote_file = "/data/log/test_results.xml" local_path = "/home/user/reports/results.xml" device.pull_file(remote_file, local_path) LOG.info(f"Pulled {remote_file} to {local_path}") # Check if file exists on device exists = device.execute_shell_command( f"test -f {remote_path} && echo 'exists'" ) # Install HAP package hap_path = "/home/user/apps/TestApp.hap" device.install_package(hap_path) LOG.info("HAP package installed successfully") # Uninstall package device.uninstall_package("com.example.testapp") # Reboot device device.reboot() device.wait_for_boot_completion(timeout=60000) LOG.info("Device rebooted successfully") # Get device properties model = device.get_property("ro.product.model") version = device.get_property("ro.build.version.release") LOG.info(f"Device: {model}, OS Version: {version}") # Start application device.execute_shell_command( "aa start -a MainAbility -b com.example.testapp" ) # Stop application device.execute_shell_command( "aa force-stop com.example.testapp" ) except HdcError as error: LOG.error(f"Device operation failed: {error}") # Device will auto-recover if possible finally: # Device connection managed by framework pass ``` -------------------------------- ### Define Unit Test Suite with Lifecycle Hooks (JavaScript) Source: https://context7.com/arkui-x/arkxtest/llms.txt This snippet demonstrates how to define a test suite using the '@ohos/hypium' library in JavaScript. It includes examples of lifecycle hooks like `beforeAll`, `beforeEach`, `afterEach`, and `afterAll`, as well as individual test cases using `it` and assertions with `expect`. This is useful for structuring and executing unit tests within the ArkUI-X framework. ```javascript import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' export default async function abilityTest() { describe('Calculator Test Suite', function () { let calculator; // Runs once before all tests in the suite beforeAll(function () { console.info('Setting up test environment'); calculator = { value: 0 }; }) // Runs before each individual test case beforeEach(function () { calculator.value = 0; }) // Runs after each individual test case afterEach(function () { console.info('Test case completed'); }) // Runs once after all tests complete afterAll(function () { console.info('Cleaning up test environment'); calculator = null; }) it('should add two numbers correctly', 0, function () { calculator.value = 5 + 3; expect(calculator.value).assertEqual(8); }) it('should handle async operations', 0, async function () { const result = await Promise.resolve(42); expect(result).assertEqual(42); }) }) } ``` -------------------------------- ### Execute XDevice Tests with Various Configurations (Bash) Source: https://context7.com/arkui-x/arkxtest/llms.txt This section details how to execute test cases using the XDevice command-line interface. It covers basic test execution, specifying devices, custom configuration files, report and test case directories, resource paths, reboot options, dry runs, retries, repeats, and device status checks. These commands are executed in a Bash environment. ```bash # Basic test execution - run specific test modules run ssts -l CalculatorTest;LoginTest # Run tests on specific device by serial number run acts -l ActsComponentTest -sn ABC123456789 # Specify custom configuration file run hits -l HitsUiTest -c /path/to/custom_config.xml # Set custom report output directory run ssts -l SstsBasicTest -rp /home/user/test_reports # Set custom test cases directory run acts -l ActsApiTest -tcpath /home/user/testcases # Set custom resource directory run hits -l HitsPerformanceTest -respath /user/resources # Reboot device before each module execution run ssts -l ModuleTest1;ModuleTest2 --reboot-per-module # Dry run to check configuration without executing run acts -l ActsTest --dryrun # Run with retry on failure run ssts -l FlakyTest --retry 3 # Repeat test execution multiple times run acts -l StressTest --repeat 5 # Combine multiple options run ssts -l SecurityTest;NetworkTest \ -sn DEV001 \ -c ./config/prod_config.xml \ -rp ./reports \ --reboot-per-module \ --retry 2 # Check device status before test execution run acts -l ActsFullTest --check-device ``` -------------------------------- ### UI Testing: Driver and Component Finding in JavaScript Source: https://context7.com/arkui-x/arkxtest/llms.txt Illustrates how to use the UI testing framework in JavaScript to create a test driver and locate UI components using various selectors like text, ID, type, and patterns. It also shows how to chain conditions and find multiple components. ```javascript import {describe, it, expect} from '@ohos.hypium' import {Driver, ON, Component, MatchPattern} from '@ohos.UiTest' export default async function uiDriverTest() { describe('UI Driver Component Finding', function() { it('find components by different selectors', 0, async function() { // Create the UI test driver let driver = Driver.create(); // Find component by text (exact match) let loginButton = await driver.findComponent(ON.text('Login')); // Find component by text with pattern matching let searchBox = await driver.findComponent( ON.text('Search', MatchPattern.CONTAINS) ); // Find component by ID let usernameField = await driver.findComponent(ON.id('username_input')); // Find component by type let textInput = await driver.findComponent(ON.type('TextField')); // Chain multiple conditions let enabledButton = await driver.findComponent( ON.text('Submit').enabled(true).clickable(true) ); // Find multiple components let allButtons = await driver.findComponents(ON.type('Button')); console.info('Found ' + allButtons.length + ' buttons'); // Check if component exists let exists = driver.assertComponentExist(ON.text('Welcome')); expect(exists).assertTrue(); }) }) } ``` -------------------------------- ### Execute Test Tasks using Test Framework Source: https://github.com/arkui-x/arkxtest/blob/master/xdevice/README.md Executes selected test cases, including compilation, execution, and result collection. The command supports specifying test lists or test files. ```bash run: This command is used to execute the selected testcases. It includes a series of processes such as use case compilation, execution, and result collection. usage: run [-l TESTLIST [TESTLIST ...] | -tf TESTFILE ``` -------------------------------- ### List Devices and Task Records in Test Framework Source: https://github.com/arkui-x/arkxtest/blob/master/xdevice/README.md Displays device information and task records. Supports listing all devices, historical task records, or records for a specific task ID. ```bash list: This command is used to display device list and task record. usage: list list history list Introduction: list: display device list list history: display history record of a serial of tasks list : display history record about task what contains specific id Examples: list list history list 6e****90 ``` -------------------------------- ### Configure XDevice Environment and Devices (XML) Source: https://context7.com/arkui-x/arkxtest/llms.txt This XML snippet demonstrates the structure for configuring the XDevice test environment, including device connections and resource paths. It specifies settings for HDC (OpenHarmony Device Connector) for both local and remote devices, serial port configurations, test case directories, and NFS mount options. This configuration is typically stored in a `user_config.xml` file. ```xml 192.168.1.100 8710 ABC123456789;DEF987654321 COM20 cmd 115200 8 1 20 /home/user/xdevice/testcases 192.168.1.50 2049 testuser testpass123 /nfs/test_resources true ``` -------------------------------- ### Manage XDevice Connected Devices (Bash) Source: https://context7.com/arkui-x/arkxtest/llms.txt This section outlines commands for managing connected test devices using the XDevice command-line interface. It includes listing all devices and their status, viewing historical test task records, and retrieving detailed information about a specific task by its ID. These commands are executed in a Bash environment. ```bash # List all connected devices and their status list # View historical test task records list history # View details of specific task by ID list 6e12a90b ``` -------------------------------- ### Trigger Device Key Events with ArkUI-X Test Source: https://context7.com/arkui-x/arkxtest/llms.txt This snippet illustrates how to simulate device key presses and key combinations within the ArkUI-X testing framework. It covers pressing the back button, triggering individual keys by their codes, and executing key combinations using modifier keys. Dependency is '@ohos.UiTest'. ```javascript import {Driver} from '@ohos.UiTest' export default async function keyEventTest() { describe('Device Key Events', function() { it('trigger device keys', 0, async function() { let driver = Driver.create(); // Press back button await driver.pressBack(); // Trigger individual key by code await driver.triggerKey(2000); // Home key await driver.triggerKey(2001); // Back key await driver.triggerKey(2017); // Power key // Trigger key combinations (modifier keys + key) // Ctrl + C (key codes: 2072 = Ctrl, 2038 = C) await driver.triggerCombineKeys(2072, 2038); // Ctrl + Shift + T (three keys) await driver.triggerCombineKeys(2072, 2073, 2044); // Example: Search shortcut await driver.triggerKey(2055); // Search key }) }) } ``` -------------------------------- ### Unit Testing: Assertion Methods in JavaScript Source: https://context7.com/arkui-x/arkxtest/llms.txt Demonstrates various assertion methods for unit testing in JavaScript, including basic equality, numeric comparisons, string and type checks, exception handling, deep equality for objects and arrays, promise state assertions, and negated assertions using not(). It utilizes the '@ohos/hypium' library. ```javascript import { describe, it, expect } from '@ohos/hypium' export default async function assertionTest() { describe('Assertion Examples', function () { // Basic equality and boolean checks it('assertEqual and boolean assertions', 0, function () { expect(100).assertEqual(100); expect(true).assertTrue(); expect(false).assertFalse(); expect(null).assertNull(); expect(undefined).assertUndefined(); }) // Numeric comparisons it('numeric comparison assertions', 0, function () { expect(10).assertLarger(5); expect(3).assertLess(7); expect(99.5).assertClose(100, 1); // Within tolerance of 1 expect(Number.NaN).assertNaN(); expect(Number.POSITIVE_INFINITY).assertPosUnlimited(); expect(Number.NEGATIVE_INFINITY).assertNegUnlimited(); }) // String and type checks it('string and type assertions', 0, function () { expect('hello world').assertContain('world'); expect('testing').assertInstanceOf('String'); expect(42).assertInstanceOf('Number'); }) // Exception and error handling it('exception assertions', 0, function () { function throwError() { throw new Error('Something went wrong') } expect(throwError).assertThrowError('Something went wrong'); }) // Deep equality for complex objects it('deep equality assertions', 0, function () { const obj1 = {x: 1, y: {z: 2}}; const obj2 = {x: 1, y: {z: 2}}; expect(obj1).assertDeepEquals(obj2); const arr1 = [1, 2, [3, 4]]; const arr2 = [1, 2, [3, 4]]; expect(arr1).assertDeepEquals(arr2); const map1 = new Map([[1, 'a'], [2, 'b']]); const map2 = new Map([[1, 'a'], [2, 'b']]); expect(map1).assertDeepEquals(map2); }) // Promise state assertions it('promise assertions', 0, function () { const pending = new Promise(() => {}); expect(pending).assertPromiseIsPending(); const resolved = Promise.resolve({data: 'success'}); expect(resolved).assertPromiseIsResolved(); expect(resolved).assertPromiseIsResolvedWith({data: 'success'}); const rejected = Promise.reject(new TypeError('validation error')); expect(rejected).assertPromiseIsRejected(); expect(rejected).assertPromiseIsRejectedWithError(TypeError); }) // Negation with not() it('negated assertions', 0, function () { expect(5).not().assertLarger(10); expect('hello').not().assertContain('goodbye'); expect(100).not().assertNaN(); expect(3).not().assertUndefined(); }) }) } ``` -------------------------------- ### Interact with UI Components using ArkUI-X Test Source: https://context7.com/arkui-x/arkxtest/llms.txt This snippet demonstrates how to interact with various UI components in ArkUI-X. It covers single clicks, double clicks, long clicks, text input, clearing text fields, retrieving component attributes, and performing scroll operations. Dependencies include '@ohos/hypium' and '@ohos.UiTest'. ```javascript import {describe, it, expect} from '@ohos/hypium' import {Driver, ON} from '@ohos.UiTest' export default async function uiInteractionTest() { describe('UI Component Interactions', function() { it('interact with UI components', 0, async function() { let driver = Driver.create(); // Single click on a button let submitButton = await driver.findComponent(ON.text('Submit')); await submitButton.click(); // Double click let imageView = await driver.findComponent(ON.type('Image')); await imageView.doubleClick(); // Long click let menuItem = await driver.findComponent(ON.text('Options')); await menuItem.longClick(); // Input text into a field let emailField = await driver.findComponent(ON.id('email_input')); await emailField.inputText('user@example.com'); // Clear text field let passwordField = await driver.findComponent(ON.id('password_input')); await passwordField.clearText(); // Get component attributes let buttonText = await submitButton.getText(); expect(buttonText).assertEqual('Submit'); let isEnabled = await submitButton.isEnabled(); expect(isEnabled).assertTrue(); let bounds = submitButton.getBounds(); console.info('Button bounds: ' + JSON.stringify(bounds)); // Scroll operations let scrollView = await driver.findComponent(ON.scrollable(true)); await scrollView.scrollToTop(500); // Speed: 500 pixels/second await scrollView.scrollToBottom(500); // Scroll search - find component by scrolling let hiddenItem = await scrollView.scrollSearch(ON.text('Hidden Item')); expect(hiddenItem).assertNotNull(); }) }) } ``` -------------------------------- ### Perform Coordinate-Based Actions with ArkUI-X Test Source: https://context7.com/arkui-x/arkxtest/llms.txt This snippet shows how to perform UI gestures and actions using screen coordinates in ArkUI-X. It includes clicking, double-clicking, long-clicking at specific coordinates, swiping, flinging, pinch gestures, and complex multi-touch actions using PointerMatrix. Dependencies include '@ohos.UiTest'. ```javascript import {Driver, ON, UiDirection, PointerMatrix} from '@ohos.UiTest' export default async function coordinateActionsTest() { describe('Coordinate-Based UI Actions', function() { it('perform coordinate-based gestures', 0, async function() { let driver = Driver.create(); // Click at specific coordinates await driver.click(300, 500); // Double click at coordinates await driver.doubleClick(400, 600); // Long click at coordinates await driver.longClick(200, 300); // Swipe gesture from one point to another await driver.swipe( 100, 500, // start x, y 100, 100, // end x, y 600 // speed in pixels/second ); // Fling gesture using points let startPoint = {x: 500, y: 800}; let endPoint = {x: 500, y: 200}; await driver.fling(startPoint, endPoint, 50, 800); // Fling in a direction await driver.fling(UiDirection.UP, 1000); await driver.fling(UiDirection.DOWN, 1000); await driver.fling(UiDirection.LEFT, 1000); await driver.fling(UiDirection.RIGHT, 1000); // Multi-finger pinch gestures on a component let imageView = await driver.findComponent(ON.type('Image')); await imageView.pinchOut(1.5); // Zoom in by 1.5x await imageView.pinchIn(0.5); // Zoom out by 0.5x // Complex multi-touch gesture using PointerMatrix let matrix = new PointerMatrix(); matrix.create(2, 10); // 2 fingers, 10 steps // Define two-finger gesture path for (let step = 0; step < 10; step++) { matrix.setPoint(0, step, {x: 100 + step * 10, y: 500}); matrix.setPoint(1, step, {x: 300 - step * 10, y: 500}); } await driver.injectMultiPointerAction(matrix, 500); // Add delay between actions await driver.delayMs(1000); }) }) } ``` -------------------------------- ### Implement Custom Test Driver with XDevice Python API Source: https://context7.com/arkui-x/arkxtest/llms.txt This Python code defines a custom test driver by inheriting from the IDriver interface. It handles test execution by setting up test kits, connecting to a device, running a shell command, parsing results, and cleaning up resources. It requires 'xdevice' library and relies on specific JSON configurations. ```python from xdevice import IDriver from xdevice import Plugin from xdevice import platform_logger from xdevice import JsonParser from xdevice import ShellHandler from xdevice import get_kit_instances from xdevice import do_module_kit_setup from xdevice import do_module_kit_teardown LOG = platform_logger("CustomDriver") @Plugin(type=Plugin.DRIVER, id="CustomTest") class CustomTestDriver(IDriver): """ Custom test driver for specialized test execution """ def __init__(self): self.result = "" self.error_message = "" self.config = None def __check_environment__(self, device_options): """Check if test environment is ready""" pass def __check_config__(self, config): """Validate test configuration""" pass def __execute__(self, request): """ Main test execution method Args: request: Test request object containing: - config: Test configuration - listeners: Result listeners - root: Test suite root descriptor """ try: # Get test configuration self.config = request.config self.config.device = request.config.environment.devices[0] # Parse test JSON configuration json_config = JsonParser(request.root.source.config_file) # Setup test kits (prerequisites) kits = get_kit_instances(json_config, self.config.resource_path, self.config.testcases_path) do_module_kit_setup(request, kits) # Get device and prepare test environment device = self.config.device device.connect() # Execute test cases test_path = "/data/test/custom_tests" command = f"cd {test_path} && ./run_tests.sh" # Create result parser parsers = get_plugin(Plugin.PARSER, "CustomParser") parser_instances = [] for listener in request.listeners: parser_instance = parsers.__class__() parser_instance.suite_name = "CustomTestSuite" parser_instance.listeners = request.listeners parser_instances.append(parser_instance) # Execute with result collection handler = ShellHandler(parser_instances) result = device.execute_shell_command( command, timeout=300000, receiver=handler ) # Process results LOG.info(f"Test execution completed with result: {result}") except Exception as error: LOG.error(f"Test execution failed: {error}") self.error_message = str(error) finally: # Cleanup test kits do_module_kit_teardown(request, kits) return True def __result__(self): """Return test execution result""" return self.result if self.result else self.error_message ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.