python+appium automation

1. Download Android SDK( https://www.androiddevtools.cn/ )If you want to try Android development, you can download Android studio. If you want to be concise, you can download SDK tools. Download the Windows version of the official installer_r24.4.1-windows.exe. After installation, there will be two startup items: AVD manager and SDK manager.
2. Enter SDK manager and download the required files, including Android SDK platform tools and Android SDK build tools under tools; Download the Android environment of the simulation environment. You can choose Android 8 / 9 / 10 / 4 to download (large volume); Download Intel X86 Emulator Accelerator (HAXM installer), Android Support Repository, Google USB Driver, Google Repository and Android Auto API Simulators under Extras. After downloading, you can open Android-AVD and try to run the simulator. There is a defined virtual machine under the Device Definitions tab. You can choose to run it or customize the virtual machine to run it yourself (if it is not successful, the screen will be black after startup). Finally, the SDK was reinstalled through idea and started successfully. It is suspected that the SDK version is too low.
3. Configure environment variable JAVA_HOME,ANDROID_ Home (from the SDK installation Path to the upper layer of avd/sdk), PYTHON_HOME (not required at this step). Add Java CLASSPATH variable.;% JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar, add the Path variable% Java of the system_ HOME%\bin;% JAVA_HOME%\jre\bin;% ANDROID_ HOME%\build-tools;% ANDROID_ HOME%\platform-tools;% ANDROID_ HOME%\tools;% PYTHON_HOME%;% PYTHON_HOME%\Scripts; C:\ProgramData\chocolatey\bin; C:\Users\dxy\AppData\Roaming\npm; D: \ nodejs (the last three are nodejs, which are usually added automatically and may need to be added manually. Chocolate may be installed when the configuration recommended by nodejs is checked, and may not be available or required when it is not checked).
4. When installing nodejs, do not check the recommended plug-in for installation. It is too large. Select to automatically add to the environment variable during installation. After installation, cmd uses npm install appium doctor - G to install appium detection tool. After installation, cmd runs appium docotr (if it is not detected, it may be that the path variable of npm above is not added). If you are sure you can install it successfully, this step is not necessary.
5. Download the Windows installation package of appium GUI for installation, start after installation, set the server address to 127.0.0.1, and start the key point option for the first time to automatically find and select JAVA_HOME and ANDROID_HOME, restart appium's server after completion, and then click the search icon in the upper right corner to create a connection.
6. Connect the real machine, open USB debugging, and click the version number in the mobile phone for many times to open the developer mode. cmd uses the adb command adb devices to view the device. When "UEUDU16B04006241 unauthorized" appears, the device is detected. Click the pop-up window on the mobile phone for authorization, and run adb devices on the computer again. At this time, it is "UEUDU16B04006241 device".
Other related commands ADB shell getprop ro build. version. Release to obtain the mobile phone system version (you can also view it on the mobile phone)
adb shell getprop ro.build.version.sdk to get the API version of mobile phone system
adb -d shell getprop ro.product.model to get the phone model
adb -d shell getprop ro.product.brand gets the name of the mobile phone manufacturer
adb shell getprop ro.serialno get the mobile phone serial number (i.e. the serial number to start adb devices)
adb shell pm list packages lists the package names of apps searched on the mobile phone
adb shell pm list packages | findstr calc filter the specified package name calc
Open the app on the mobile phone and run adb shell dumpsys window windows | grep -E "mFocusedApp" to view the currently active app information. It mainly needs appPackage and appActivity. The package name is consistent with that obtained above. appActivity is generally followed / followed
Enter the real machine information in appium

{
"platformName": "Android",
"platformVersion": "9.0",
"deviceName": "UEUDU16B04006241",
"appPackage": "com.shidegroup.newtrunk",
"appActivity": "com.shidegroup.newtrunk.MainActivity",
"noResert": true
}

Click start session after completing the form. Multiple apps will be installed on the phone: appium settings and uiautomator2 Server and uiautomator2 Test, confirm the installation
7. Many virtual machines on the night God simulator are incompatible with browsers, and avd virtual machines cannot install apps. According to Baidu, x86 is selected for the cup/abi option, while most apps use arm in others. You can download and use it in idea. Currently only Android 7.0 is supported 1.1, 1G in size, so it's gone
8. Simple test on calculator simulator:
Copy platform in sdk_ ADB under tools Exe to bin under the night God installation directory to overwrite the existing ADB exe. Make another copy and change the name to nox_adb.exe overwrite nox_adb.exe. Start the night God simulator (you can use duokai to modify the Android version, which is currently up to 7). Use cmd to enter the night God bin and run nox_adb, check whether it is connected. After entering the app, run adb shell dumpsys window windows | grep -E "mFocusedApp" to check the package information of the computer (you need to install the calculator first, and the super calculator produced by Youdao). The positioning of Android: Android is actually the same as selenium and depends on many packages of selenium. You can use xpath, id, Name and other positioning (in the actual development, we must standardize the writing specification of the development and provide a unique positioning id. you see, appium also suggests this). At the same time, the exception information thrown also refers to selenium's NoSuchElement, and the waiting method also uses selenium's WebDriverWait class. The main new addition is find_element_by_android_uiautomator these methods can be viewed on Baidu. The following is a test example

```python
# -*- coding:utf-8 -*-
import time
import unittest

from appium import webdriver
from BeautifulReport import BeautifulReport  # Better looking report than HTML testreport
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class MyTests(unittest.TestCase):
    # Methods to be performed before testing
    def setUp(self):
        desired_caps = {'platformName': 'Android',  # Platform name
                        'platformVersion': '7.1.2',  # System version number 
                        'deviceName': '127.0.0.1:62001',  # Equipment name. If it is a real machine, check it in 'settings - > about mobile phone - > device name'
                        'appPackage': 'com.youdao.calculator',  # Package name of apk
                        'appActivity': 'com.youdao.calculator.activities.MainActivity',  # activity name
                        'noReset': 'true' #Clear cache
                        }
        self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps) # connect Appium
        self.driver.implicitly_wait(8)
        self.waiter = WebDriverWait(self.driver, 20)

    @BeautifulReport.add_test_img("test_calculator.png")
    def test_calculator(self, t=500, n=4):
        """Calculator test"""
        self.waiter.until(expected_conditions.invisibility_of_element_located(
            self.driver.find_elements_by_android_uiautomator('new UiSelector().textMatches("calculation")'))) #Wait until you enter the calculator page
        self.driver.tap([(290, 860)])  # Click 7
        self.driver.tap([(620, 860)])  # Click the * sign
        self.driver.tap([(410, 860)])  # Click 8
        self.driver.tap([(620, 1150)])  # Click equal
        time.sleep(2)  # Waiting for calculation results
        result = self.driver.find_element_by_android_uiautomator(
            'new UiSelector().resourceId("numericResultDiv").childSelector(className("android.view.View"))').text  # Get calculation results
        print(result)
        result2 = self.driver.find_element_by_xpath(
            "//android. view. View[@resource-id='numericResultDiv']/android. view. View "). Text # XPath to locate and obtain the calculation result
        print(result2)
        if result != '$$=56​':
            assert False

    # Method to execute after test
    def tearDown(self):
        self.driver.quit()
# -*- coding:utf-8 -*-
import os
import time
import unittest
from BeautifulReport import BeautifulReport

discover = unittest.defaultTestLoader.discover(start_dir='./', pattern="app_test1.py")
runner = BeautifulReport(discover)
runner.report(filename="Test report", description="This test report contains a simple test of the supercomputer")
The following is the running result
![Insert picture description here](https://img-blog.csdnimg.cn/20210424142237304.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM1OTk5MDE3,size_16,color_FFFFFF,t_70)

Keywords: Python Android Selenium

Added by renno on Sun, 20 Feb 2022 07:03:21 +0200