You think Shell is just a command line? Read this article and empower your work

Posted by woza_uk on Fri, 21 Jan 2022 04:44:10 +0100

What is Shell? Many people think that the Shell is the command line, which can be Baidu out one by one. And on your resume, you only write that you are familiar with Linux? Today, I will use Mobai App to explain how to use it
Shell to operate Android devices for automated testing.

1 Environmental preparation
First, we need to prepare a mobile phone or an Android simulator. Then you need to configure the Android development environment on your computer.

  • Download Android SDK: download the corresponding zip package according to the system version. Please download according to your own system.

  • Unzip the zip package and a Tools Directory will be generated. You need to create a new sdk directory, and then move the tools directory to the sdk directory.

        mkdir sdk  
            mv tools sdk
    
  • Set the environment variable and add Android according to the location of the new sdk directory_ Path to home:

        export ANDROID_HOME=sdk Directory location for  
              
                  export PATH=$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin
    
  • Download the toolkit using SDK manager

        sdkmanager "platform-tools" "build-tools;28.0.3"
    

The SDK manager is located in SDK / tools / bin / SDK manager.

2 ADB use
Android debug bridge (adb) is a general-purpose command-line tool that allows you to connect with an emulator instance or Android
Communicate with the device. It can facilitate the operation of various devices, such as installing and debugging applications, and provide support for Unix
Access to the shell, which can be used to run various commands on the simulator or connected device. As a client server program, the tool includes three components:

  • Client: this component sends commands. The client runs on the development computer. You can invoke the client from the command line terminal by issuing the adb command.
  • Daemon: this component runs commands on the device. The daemon runs as a daemon on each emulator or device instance.
  • Server: this component manages the communication between the client and the daemon. The server runs as a background process on the development computer.
    You can find the adb tool in SDK / platform tools /.

We usually use adb devices to view the Android devices connected to the computer, and use adb shell to open the terminal on the Android device to execute various commands. Using adb
Log cat to view the log information generated by Android devices.

If you do not want to use the usb cable to connect the Android device, you can use the adb tcpip port to start a specified port on the Android device, and then use adb connect
Android device ip port: connect Android device remotely.

3. Execute commands under ADB shell

uiautomator

Uiautomator is a java library that contains API s for creating custom functional UI tests and an execution engine for automatically executing and running tests. Using uiautomator
Help to view help information. Here we mainly use uiautomator
Dump to get the XML file of the UI hierarchy of the current screen. Default location for storing files / sdcard/window_dump.xml, or you can specify the location of uiautomator
dump /data/local/tmp/ui.xml.

input

Input can be used to simulate various input operations, such as sending text, clicking controls and sliding coordinates. Use input to view help information.

  • input text ab c: enter text abc
  • input tap x coordinate y coordinate: click the coordinate position x, y
  • Input swing X1 coordinate y1 coordinate x2 coordinate y2 coordinate: slide from x1, y1 coordinate to X2, y2 coordinate

4 Practice
Well, after we have configured the Android development environment, roughly understood the function of adb commands, and known the uiautomator and input commands on Android devices, we will begin to focus on today's key, and use these commands to combine into automatic operations.

First of all, we need to find an APP for our practice. Today we choose "Moby bike". You can download the installation package file here.

After downloading, we connect the Android device to the computer using usb cable. Use adb devices to confirm whether the device is connected successfully.

The device has been successfully connected. We need to install the "Moby bike" Application on the Android device and execute adb install
Moby bike installation file, "some mobile phones have strict permission management. You may need to click on the mobile phone to agree to install this application."

Enter the terminal of Android device

We first open the Moby bike application, and then check the source code of the page

        uiautomator dump --compressed /data/local/tmp/ui.xml && cat /data/local/tmp/ui.xml

A is generated after execution xml file. The file structure is as follows. Each control consists of.

        <?xml version='1.0' encoding='UTF-8' standalone='yes' ?><hierarchy rotation="0">  
              
                  <node index="0" text="You haven't finished mobile phone verification yet. Please verify your mobile phone first" resource-id="com.mobike.mobikeapp:id/text" class="android.widget.TextView" package="com.mobike.mobikeapp" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[48,259][771,365]" /></node>  
                        
                            <node index="1" text="Sign in" resource-id="com.mobike.mobikeapp:id/action" class="android.widget.TextView" package="com.mobike.mobikeapp" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[819,261][1032,362]" /></node>  
                                  
                                        
                                            Omitted here n Multiline......</hierarchy>

We can split according to and structure. Command behavior used:

        cat /data/local/tmp/ui.xml | sed 's#<node #^<node #g' |tr '^' '\n'

sed means to replace the characters containing < node with ^ < node. Then use the tr command to replace the ^ character with the \ n character. \N means line feed.

click
Find the X and Y axis coordinates of the control center point according to the boundaries = "[x1, Y1] [X2, Y2]" attribute in the control. The calculation method is (x1+x2)/2, (y1+y2)/2``

        cat /data/local/tmp/ui.xml | sed 's#<node #^<node #G '| tr' ^ '\ n' | grep '"Moby bike" | awk - f' \ \ [| \ \] |, '{print ($2 + $5) / 2, ($3 + $6) / 2}'

awk -F specifies the delimiter. '\ [| \ \] |, 'this string matches "[],

”These three characters. Where \ \ two backslashes represent escape characters and | vertical lines represent or. The whole is to match "left bracket" or "right bracket" or "comma".

Then use the x and y coordinates obtained by the above method to click the application icon input tap 167.5 219. Finally, write a function. As long as you pass the name of the control, you can click the corresponding icon.

        # Click function  
            function click(){  
                adb shell uiautomator dump --compressed /data/local/tmp/ui.xml  
                    XY=$(adb shell cat /data/local/tmp/ui.xml | sed 's#<node #^<node #g' |tr '^' '\n' | grep "$@"| awk -F '\\[|\\]|,' '{print ($2+$5)/2,($3+$6)/2}')  
                        echo $XY  
                              adb shell input tap $XY  
                                  }

Click the coordinates, because my mobile phone displays two coordinates about the Mobai application, one is the application icon and the other is the application text. Select one of them.

        click 'text="Mobike"'  
            click 'content-desc="Mobike"'

Enter text

        # Enter text  
            function send_keys(){  
                adb shell input text "$@"  
                    }

slide

The wm size command can view the screen resolution, and then extract the resolution value adb shell wm size |awk -F '| x' {print ,}
, a space or x is used as the separator.

        # Sliding function  
            function swipe(){  
                  # Get screen size  
                      SIZE=$(adb shell wm size)  
                          echo $SIZE  
                              # The coordinate awk -v for starting sliding sets a variable x, the received variable content is $1, and $1 is the position parameter.  
                                  START=$(echo $SIZE |awk -v x=$1 -v y=$2 -F ' |x' '{print $3*x,$4*y}')  
                                      echo start: $START  
                                          # Coordinates of the end slide  
                                              END=$(echo $SIZE | awk -v x=$3 -v y=$4 -F ' |x' '{print $3*x,$4*y}')  
                                                  echo end: $END  
                                                      # slide  
                                                          adb shell input swipe $START $END  
                                                              }

Slide with swipe x1 y1 x2 y2. For example (the following values are random):

Slide from right to left: swipe 0.3 0.8 0.7 0.8
Slide from left to right: swipe 0.7 0.8 0.3 0.8
Slide from top to bottom: swipe 0.8 0.7 0.8 0.3
Slide from bottom to top: swipe 0.8 0.3 0.8 0.7

5 actual operation effect

Open the APP and stay for 12 seconds

         function main(){  
                 echo 'Open the Moby bike app'  
                         click 'content-desc="Mobike"'  
                                 echo 'Wait 12 seconds'  
                                     
                                         
                                                 sleep 12

The overall operation effect is like this.

Close the prompt and log in

             echo 'Close prompt'
                 
                         click 'resource-id="com.mobike.mobikeapp:id/btn_close"'  
                                 echo 'Wait 2 seconds'  
                                         sleep 2  
                                                 echo 'Click "login"'  
                                                         click "Sign in"  
                                                                 echo 'Wait 2 seconds'  
                                                                     
                                                                         
                                                                                 sleep 2

The overall operation effect is like this.

Enter your phone number and log in

             echo 'Enter "phone number"'  
                     send_keys 13718321932  
                             echo 'Wait 2 seconds'  
                                     sleep 2  
                                             echo 'Click next“'  
                                                     click 'text="next step"'  
                                                         
                                                             
                                                                 }
                                                                     
                                                                           
                                                                               
                                                                                   
                                                                                       main  

The overall operation effect is as follows (the mobile phone number in the figure above is filled in randomly).

6 at the end
**
**
Of course, script automation is much more than that. You need to know more. For example, awk and sed command functions. What other parameters can adb use? How does adb work?

If you want a small partner of Mobai automation script, you can also add a small assistant wechat to reply to "phase 10" and join the group. More dry goods at Hogwarts Testing Institute, issue 10: Linux script automation.

-Today's interaction-

Welcome to leave a message and share it with other test partners who love learning

(don't forget to press and hold add little assistant wechat,

(you can join the group by replying to "issue 10")

_ ****_

Come to Hogwarts test and development society to learn more advanced technologies of software testing and test development. The knowledge points include web automated testing, app automated testing, interface automated testing, test framework, performance testing, security testing, continuous integration / continuous delivery / DevOps, test left, test right, precision testing, test platform development, test management, etc, The course technology covers bash, pytest, junit, selenium, appium, postman, requests, httprunner, jmeter, jenkins, docker, k8s, elk, sonarqube, Jacobo, JVM sandbox and other related technologies, so as to comprehensively improve the technical strength of test and development engineers
QQ communication group: 484590337
The official account TestingStudio
Video data collection: https://qrcode.testing-studio.com/f?from=CSDN&url=https://ceshiren.com/t/topic/15844
Click for more information

Topics: Java Android Apache software testing Testing