All Products
Search
Document Center

Mobile Testing:Write an iOS test script

Last Updated:Jul 10, 2023

Mobile Testing supports automated testing code that is written based on Appium. This topic describes how to use Appium to perform functional testing on iOS 10 devices.

Important

Mobile Testing supports third-party libraries such as pytest, unittest, and Robot Framework. If you want to use another framework, contact technical support.

Prerequisites

  • You are familiar with how to use Appium for automated testing. For more information, see Appium documentation.

  • You have basic Python programming skills.

Configure environments

In this topic, iOS 10 is used to show the required environments:

  • macOS 10.11.5 and later

  • Xcode 8.0 and later

  • Appium 1.6.0 and later

Create a Capabilities file

Write a Capabilities file in the Python language to specify the test environment required to execute the test script. The file is named desired_capabilities.py.

The file contains the get_uri() and get_desired_capabilities() functions.

Function

Description

get_desired_capabilities()

Queries the parameters of the current session.

You can configure the parameters based on your business requirements. For more information, see Appium Desired Capabilities.

get_uri()

Returns the URL of the Appium server.

Sample code

#!/usr/bin/env python

import sys

def get_desired_capabilities():
    desired_caps = {
        'platformName': 'iOS',
        'platformVersion': '10.0',
        'deviceName': 'iPhone 6s',
        'udid': '36317c0f81086d7f4f99a9771179720b7962****',
        'realDeviceLogger':'/usr/local/lib/node_modules/deviceconsole/deviceconsole',
        'app': '/Users/adam/iosapp.app',
        'bundleId':'net.oschina.iosapp',
        'newCommandTimeout': 60,    
        'automationName': 'Appium',
        'noReset': True
    }

    return desired_caps

def get_uri():
    return "http://localhost:56000/wd/hub"

def flushio():
    sys.stdout.flush()

Parameter description

1. Ten parameters are configured in the get_desired_capabilities() function.

Parameter

Description

platformName

The system type of the test device.

platformVersion

The system version of the test device.

deviceName

The name of the test device.

udid

The ID of the test device.

realDeviceLogger

The storage path of the deviceconsole tool, which is used to query the logs of the test device.

app

The storage path of the app installer.

If this parameter is not configured, the bundle ID of the currently installed app on the phone is used as the storage path.

bundleId

The bundle ID of the app.

newCommandTimeout

The maximum time interval allowed between two commands.

If the time interval between two commands exceeds the specified value, the Appium server ends the current session.

automationName

The automation engine used in the current session.

  • If the system version of the device is earlier than Android 4.2, set the value to Selendroid.

  • If the system version of the device is iOS 4.2 or Android 4.2 or later, set the value to Appium.

noReset

Specifies whether to reset the app before the current session ends.

2. By default, the listener port of the on-premises Appium server is set to 50000. In this case, the return value of get_uri() is http://localhost:50000/wd/hub.

Note

desired_capabilities.py is used only to execute and verify the test script locally. After the test script is packaged and uploaded, the Mobile Testing platform generates a file to replace the desired_capabilities.py file.

Create an entry script file

Write a test script in the Python language as an entry to perform automated testing. The script file is named main.py.

Sample code and description:

# -*- coding: utf-8 -*-

from appium import webdriver

# Import the desired_capabilities.py file that was created in the root directory.
import desired_capabilities

# Use unittest of Python as the unit testing tool.
from unittest import TestCase

# Use unittest of Python as the unit testing tool.
import unittest

# Use the time.sleep(xx) function to suspend the execution of the current thread for a specific number of seconds.
import time

class MqcTest(TestCase):

    def setUp(self):
        # Query the specified capabilities and notify the Appium server to create the corresponding session. 
        desired_caps = desired_capabilities.get_desired_capabilities()
        # Query the URL of the server.
        uri = desired_capabilities.get_uri()
        # Create a session and query the driver object that encapsulates all device operations. 
        self.driver = webdriver.Remote(uri, desired_caps)
        # Wait for the app to fully load.
        time.sleep(3)

    # Use the first test case to close dialog boxes that are detected.
    def test_case_a_dismiss_alert(self):
        while True:
            time.sleep(3)
            alertEle = self.driver.find_elements_by_class_name("XCUIElementTypeAlert")
            if alertEle:
                print 'find an alert'
                notAllowBtn = self.driver.find_element_by_xpath("//XCUIElementTypeButton[@label='Forbid']")
                notAllowBtn.click()
            else:
                break

    # Use the second test case to log on to the app.
    def test_case_b_login(self):
        # Retrieve the left button in the navigation bar.
        leftBtn = self.driver.find_element_by_xpath("//XCUIElementTypeButton[@label='navigationbar sidebar']")
        leftBtn.click()
        time.sleep(3)

        # Retrive the Click Profile Picture to Log On button.
        potraitEle = self.driver.find_element_by_xpath("//XCUIElementTypeStaticText[@label='Click Profile Picture to Log On']")
        potraitEle.click()
        time.sleep(3)

        # Retrieve the username and password input fields
        tfEle = self.driver.find_element_by_class_name("XCUIElementTypeTextField")
        stfEle = self.driver.find_element_by_class_name("XCUIElementTypeSecureTextField")
        tfEle.send_keys("mqctest".decode('UTF-8'))
        time.sleep(1)
        stfEle.send_keys("123456".decode('UTF-8'))
        time.sleep(2)

        # Retrieve the Log On button.
        loginBtn = self.driver.find_element_by_xpath("//XCUIElementTypeButton[@label='Log On']")
        loginBtn.click()

        # Wait for the logon to succeed.
        time.sleep(5)

    def tearDown(self):
        # The test ends. Exit the session.
        self.driver.quit()

if __name__ == '__main__':
    try: unittest.main()
    except SystemExit: pass
Note

The Mobile Testing platform implements functional testing by executing the test script in the main.py file.

Start the Appium server

Run the appium command on the CLI to start the Appium server. Example: appium -p 50000.

Parameters

Parameter

Description

-p

Specifies the listener port of the Appium server.

-a

Specifies the IP address of the Appium server.

-selendroid-port

Specifies the port of Android Debug Bridge (adb) in Selendroid mode.

-U

Specifies the serial number of the test device when multiple devices are connected to the Appium server.

--full-reset

Specifies to clean up the device after the test case is executed.

Execute the test script

  1. Connect a mobile phone for which the developer mode is enabled to your computer.

  2. Run the python main.py -v command on the CLI to execute the test script and check whether the features that you want to test work as expected.

Submit the test script to Mobile Testing

1. Package the test file as a ZIP file.

Note

The main.py file must be stored in the root directory.

2. In the Mobile Testing console, create a script by uploading the ZIP file. The script is used for subsequent functional testing on Android devices. For more information, see Create a script.